diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/GameCrashWindow.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/GameCrashWindow.java index c45bcbaa9..4e815882c 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/GameCrashWindow.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/GameCrashWindow.java @@ -142,7 +142,7 @@ public class GameCrashWindow extends Stage { String log; try { - log = FileUtils.readText(latestLog); + log = FileUtils.readTextMaybeNativeEncoding(latestLog); } catch (IOException e) { LOG.warning("Failed to read logs/latest.log", e); return pair(new HashSet(), new HashSet()); diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/util/io/FileUtils.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/util/io/FileUtils.java index ba257a94c..4306b99ab 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/util/io/FileUtils.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/util/io/FileUtils.java @@ -17,6 +17,8 @@ */ package org.jackhuang.hmcl.util.io; +import org.glavo.chardet.DetectedCharset; +import org.glavo.chardet.UniversalDetector; import org.jackhuang.hmcl.util.Lang; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.function.ExceptionalConsumer; @@ -128,6 +130,24 @@ public final class FileUtils { return new String(Files.readAllBytes(file), charset); } + public static String readTextMaybeNativeEncoding(Path file) throws IOException { + byte[] bytes = Files.readAllBytes(file); + + if (OperatingSystem.NATIVE_CHARSET == UTF_8) + return new String(bytes, UTF_8); + + UniversalDetector detector = new UniversalDetector(); + detector.handleData(bytes); + detector.dataEnd(); + + DetectedCharset detectedCharset = detector.getDetectedCharset(); + if (detectedCharset != null && detectedCharset.isSupported() + && (detectedCharset == DetectedCharset.UTF_8 || detectedCharset == DetectedCharset.US_ASCII)) + return new String(bytes, UTF_8); + else + return new String(bytes, OperatingSystem.NATIVE_CHARSET); + } + /** * Write plain text to file. Characters are encoded into bytes using UTF-8. *