From d70712a18f9bc516eb4a16d2c59ee21bf9049649 Mon Sep 17 00:00:00 2001 From: Glavo Date: Sun, 27 Apr 2025 22:15:30 +0800 Subject: [PATCH] =?UTF-8?q?Fix=20#3546:=20=E4=BF=AE=E5=A4=8D=E6=B8=B8?= =?UTF-8?q?=E6=88=8F=E5=B4=A9=E6=BA=83=E7=AA=97=E5=8F=A3=E4=B9=B1=E7=A0=81?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98=20(#3867)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jackhuang/hmcl/ui/GameCrashWindow.java | 2 +- .../org/jackhuang/hmcl/util/io/FileUtils.java | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) 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. *