Java准确获取文件编码
时间: 2024-01-16 09:02:20 浏览: 24
要准确获取文件编码,可以使用 Java NIO 包中的 CharsetDetector 类来进行自动检测。以下是一个示例代码:
```java
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import org.mozilla.universalchardet.UniversalDetector;
public class FileCharsetDetector {
public static void main(String[] args) {
File file = new File("path/to/file");
if (file.exists()) {
String charset = detectCharset(file);
System.out.println("Charset: " + charset);
} else {
System.out.println("File not found.");
}
}
private static String detectCharset(File file) {
String charset;
try (InputStream inputStream = new FileInputStream(file)) {
byte[] buf = new byte[4096];
UniversalDetector detector = new UniversalDetector(null);
int nread;
while ((nread = inputStream.read(buf)) > 0 && !detector.isDone()) {
detector.handleData(buf, 0, nread);
}
detector.dataEnd();
charset = detector.getDetectedCharset();
detector.reset();
} catch (IOException e) {
charset = null;
}
if (charset == null) {
// 如果自动检测失败,则可以使用默认编码(如UTF-8)
charset = Charset.defaultCharset().name();
}
return charset;
}
}
```
这个示例程序使用了 Mozilla Universal Charset Detector 来进行自动检测,它可以检测多种编码,包括 GB2312、GBK、UTF-8 等。如果自动检测失败,则使用默认编码(如 UTF-8)。