java 如何查看编码格式
查看文件编码格式
使用 java.nio.charset.Charset 类可以检测文件的编码格式。以下是一个示例代码片段:
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;
public class EncodingDetector {
public static void main(String[] args) throws IOException {
File file = new File("example.txt");
Charset charset = FileUtils.detectCharset(file);
System.out.println("文件编码: " + charset.displayName());
}
}
需要添加 Apache Commons IO 依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
查看字符串编码格式
字符串在 Java 内部始终以 UTF-16 格式存储。要查看字节数组的编码,可以使用以下方法:

String str = "示例文本";
byte[] bytes = str.getBytes("UTF-8"); // 指定编码格式
System.out.println("字节数组编码: UTF-8");
检测字节流编码
使用 ICU4J 库可以更准确地检测字节流的编码:
import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
public class EncodingCheck {
public static void main(String[] args) {
byte[] data = ... // 获取字节数据
CharsetDetector detector = new CharsetDetector();
detector.setText(data);
CharsetMatch match = detector.detect();
System.out.println("检测到的编码: " + match.getName());
}
}
需要添加 ICU4J 依赖:

<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>71.1</version>
</dependency>
检查系统默认编码
获取 JVM 默认编码格式:
System.out.println("系统默认编码: " + System.getProperty("file.encoding"));
转换编码格式
如果需要转换编码格式,可以使用 String 类的构造函数:
byte[] utf8Bytes = "文本".getBytes("UTF-8");
String str = new String(utf8Bytes, "GBK"); // 从UTF-8转换为GBK






