Fix #3546: 修复游戏崩溃窗口乱码的问题 (#3867)

This commit is contained in:
Glavo 2025-04-27 22:15:30 +08:00 committed by GitHub
parent 05c5b53c52
commit d70712a18f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 21 additions and 1 deletions

View File

@ -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<CrashReportAnalyzer.Result>(), new HashSet<String>());

View File

@ -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.
* <p>