java 如何输出中文
在Java中输出中文
确保Java程序正确输出中文需要检查编码设置和环境配置。以下是关键步骤:
设置文件编码为UTF-8
源代码文件需保存为UTF-8格式。在IDE(如Eclipse或IntelliJ)中,可通过文件属性或全局设置调整编码。
编译时指定编码参数
使用-encoding参数确保编译器正确读取源文件:

javac -encoding UTF-8 YourProgram.java
控制台输出编码匹配
Windows默认控制台编码为GBK,可能导致乱码。可通过以下方式解决:
- 临时修改控制台编码为UTF-8:
chcp 65001 - 或在代码中转换编码:
String text = "中文"; byte[] bytes = text.getBytes("UTF-8"); System.out.println(new String(bytes, "GBK"));
IDE配置调整
在IDE中运行程序时,确保运行配置的编码设置为UTF-8。例如IntelliJ中:

- 进入
Run -> Edit Configurations - 在
VM options中添加:-Dfile.encoding=UTF-8
文件读写编码处理
读写文件时显式指定UTF-8编码:
// 写入文件
try (Writer writer = new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8")) {
writer.write("中文内容");
}
// 读取文件
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"), "UTF-8"))) {
String line = reader.readLine();
}
数据库连接编码
若涉及数据库操作,在连接字符串中指定字符集:
String url = "jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8";






