From 207b4d003384b048abe069e4888e980741d7bbf6 Mon Sep 17 00:00:00 2001 From: Glavo Date: Fri, 26 Jan 2024 21:20:29 +0800 Subject: [PATCH] Fix #2687 (#2688) * Fix #2687 * fix checkstyle --- .../jackhuang/hmcl/ui/nbt/NBTFileType.java | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/nbt/NBTFileType.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/nbt/NBTFileType.java index 4b35a6693..02dbbb844 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/nbt/NBTFileType.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/nbt/NBTFileType.java @@ -9,6 +9,7 @@ import org.apache.commons.compress.utils.BoundedInputStream; import org.jackhuang.hmcl.util.io.FileUtils; import java.io.*; +import java.util.Arrays; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; @@ -17,8 +18,22 @@ public enum NBTFileType { COMPRESSED("dat", "dat_old") { @Override public Tag read(File file) throws IOException { - try (InputStream in = new GZIPInputStream(new FileInputStream(file))) { - Tag tag = NBTIO.readTag(in); + try (BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(file))) { + fileInputStream.mark(3); + byte[] header = new byte[3]; + if (fileInputStream.read(header) < 3) { + throw new IOException("File is too small"); + } + fileInputStream.reset(); + + InputStream input; + if (Arrays.equals(header, new byte[]{0x1f, (byte) 0x8b, 0x08})) { + input = new GZIPInputStream(fileInputStream); + } else { + input = fileInputStream; + } + + Tag tag = NBTIO.readTag(input); if (!(tag instanceof CompoundTag)) throw new IOException("Unexpected tag: " + tag); return tag;