在 CentOS 上用 javac 编译 Java 出现乱码,通常不是 Java 本身的问题,而是系统/终端编码 ≠ 文件编码导致的。下面按最常见情况一步步解决。
locale
正常应该是:
LANG=zh_CN.UTF-8
LC_ALL=zh_CN.UTF-8
如果不是 UTF-8,先改:
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8
localectl set-locale LANG=zh_CN.UTF-8
或编辑:
vi /etc/locale.conf
内容:
LANG="zh_CN.UTF-8"
查看文件编码:
file -i YourFile.java
如果是 iso-8859-1 / gbk,而系统是 UTF-8,就会乱码。
javac -encoding UTF-8 YourFile.java
如果是 GBK 文件:
javac -encoding GBK YourFile.java
如果你是用:
请检查:
java -Dfile.encoding=UTF-8 YourMainClass
在 pom.xml 中加:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
locale 是 UTF-8javac -encoding UTF-8如果你愿意,可以把:
locale 输出file -i xxx.java 输出发出来,我可以帮你精准定位是哪一层乱码。