java获取文件编码格式,然后读取此文件,适用于任何格式的文件。
- 导包。
<dependency><groupId>com.googlecode.juniversalchardet</groupId><artifactId>juniversalchardet</artifactId><version>1.0.3</version>
</dependency>
- 写方法
public static String detect(String path) throws IOException {UniversalDetector detector = new UniversalDetector(null);try (InputStream is = new FileInputStream(path)) {byte[] buf = new byte[4096];int len;while ((len = is.read(buf)) > 0 && !detector.isDone()) {detector.handleData(buf, 0, len);}}detector.dataEnd();String encoding = detector.getDetectedCharset();detector.reset();return encoding;
}
- 调用
String filePath = path;
String fileEncoding = detect(filePath);
- 根据读取的编码读取文件
List<String> lines = null;
lines = Files.readAllLines(Paths.get(filePath), Charset.forName(fileEncoding ));
lines 就是所有读取内容。