java 如何查看编码格式
查看文件编码格式的方法
使用 java.nio.charset.Charset 类可以检测文件的编码格式。以下是一个示例代码片段:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class DetectEncoding {
public static void main(String[] args) throws IOException {
Path path = Paths.get("yourfile.txt");
Charset charset = Charset.defaultCharset();
System.out.println("Detected encoding: " + charset.displayName());
}
}
使用第三方库检测编码
Apache Tika 和 juniversalchardet 是常用的编码检测库。以下是使用 juniversalchardet 的示例:
import org.mozilla.universalchardet.UniversalDetector;
public class EncodingDetector {
public static String detectEncoding(byte[] bytes) throws IOException {
UniversalDetector detector = new UniversalDetector(null);
detector.handleData(bytes, 0, bytes.length);
detector.dataEnd();
return detector.getDetectedCharset();
}
}
读取文件时指定编码
在读取文件时可以明确指定编码格式:
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream("file.txt"),
StandardCharsets.UTF_8
)
);
获取系统默认编码
获取 JVM 默认编码:
String defaultEncoding = System.getProperty("file.encoding");
常见编码格式
Java 支持的常见编码格式包括:
- UTF-8
- ISO-8859-1
- US-ASCII
- UTF-16
- GBK
- Big5







