java io如何转码
使用 InputStreamReader 和 OutputStreamWriter
InputStreamReader 和 OutputStreamWriter 是 Java IO 中用于字符转码的核心类。通过指定字符编码,可以将字节流转换为字符流,或反之。

import java.io.*;
public class CharsetExample {
public static void main(String[] args) throws IOException {
// 从文件读取字节流并转为 UTF-8 字符流
try (InputStreamReader reader = new InputStreamReader(
new FileInputStream("input.txt"), "UTF-8")) {
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
}
// 将字符流以 GBK 编码写入文件
try (OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream("output.txt"), "GBK")) {
writer.write("这是测试文本");
}
}
}
使用 Files 类(Java NIO)
Java NIO 的 Files 类提供了更简洁的方法读取和写入文件,支持直接指定字符编码。

import java.nio.file.*;
import java.nio.charset.*;
public class NIOCharsetExample {
public static void main(String[] args) throws IOException {
// 读取文件内容并指定编码(UTF-8)
String content = Files.readString(Paths.get("input.txt"), StandardCharsets.UTF_8);
// 写入文件并指定编码(GBK)
Files.write(Paths.get("output.txt"),
content.getBytes(Charset.forName("GBK")));
}
}
处理字符串编码转换
若需直接转换字符串的编码,可通过 String 的 getBytes() 和 new String() 方法实现。
public class StringEncodingExample {
public static void main(String[] args) throws UnsupportedEncodingException {
String original = "测试文本";
// 将字符串从 UTF-8 转为 ISO-8859-1
byte[] isoBytes = original.getBytes("ISO-8859-1");
String decoded = new String(isoBytes, "ISO-8859-1");
System.out.println(decoded);
}
}
注意事项
- 确保目标编码支持所需字符(如中文需使用
UTF-8或GBK)。 - 处理文件时,始终显式指定编码以避免平台默认编码差异。
- 异常处理:捕获
UnsupportedEncodingException或IOException。






