1717 */
1818package org .jackhuang .hmcl .util .io ;
1919
20+ import org .glavo .chardet .DetectedCharset ;
21+ import org .glavo .chardet .UniversalDetector ;
22+
2023import java .io .*;
24+ import java .nio .channels .Channels ;
25+ import java .nio .channels .FileChannel ;
2126import java .nio .charset .Charset ;
27+ import java .nio .file .Files ;
28+ import java .nio .file .Path ;
2229import java .util .zip .GZIPInputStream ;
2330
31+ import static java .nio .charset .StandardCharsets .*;
32+ import static org .jackhuang .hmcl .util .platform .OperatingSystem .NATIVE_CHARSET ;
33+
2434/**
2535 * This utility class consists of some util methods operating on InputStream/OutputStream.
2636 *
@@ -33,6 +43,25 @@ private IOUtils() {
3343
3444 public static final int DEFAULT_BUFFER_SIZE = 8 * 1024 ;
3545
46+ public static BufferedReader newBufferedReaderMaybeNativeEncoding (Path file ) throws IOException {
47+ if (NATIVE_CHARSET == UTF_8 )
48+ return Files .newBufferedReader (file );
49+
50+ FileChannel channel = FileChannel .open (file );
51+ try {
52+ long oldPosition = channel .position ();
53+ DetectedCharset detectedCharset = UniversalDetector .detectCharset (channel );
54+ Charset charset = detectedCharset != null && detectedCharset .isSupported ()
55+ && (detectedCharset .getCharset () == UTF_8 || detectedCharset .getCharset () == US_ASCII )
56+ ? UTF_8 : NATIVE_CHARSET ;
57+ channel .position (oldPosition );
58+ return new BufferedReader (new InputStreamReader (Channels .newInputStream (channel ), charset ));
59+ } catch (Throwable e ) {
60+ closeQuietly (channel , e );
61+ throw e ;
62+ }
63+ }
64+
3665 /**
3766 * Read all bytes to a buffer from given input stream. The stream will not be closed.
3867 *
0 commit comments