Java项目必须显式统一设置UTF-8编码:编译阶段用-javac -encoding UTF-8、Maven配encoding、Gradle设compileJava.options.encoding;运行阶段加-Dfile.encoding=UTF-8;IDE需同步全局、项目及properties文件编码;IO与网络操作须显式指定StandardCharsets.UTF_8,properties文件须无BOM。
Java项目默认使用系统编码,跨平台时极易出现中文乱码,必须显式统一设置为UTF-8。
-encoding参数即使源文件保存为UTF-8,javac默认按系统编码读取,Windows上常为GBK,导致编译时报错或生成错误字节码。
javac调用都显式指定-encoding UTF-8,例如:javac -encoding UTF-8 src/com/example/Hello.java
pom.xml中配置maven-compiler-plugin的encoding属性为UTF-8
build.gradle中设置compileJava.options.encoding = "UTF-8"
-Dfile.encoding
System.getProperty("file.encoding")返回的值决定String.getBytes()、new String(byte[])等操作的默认编码,不设则继承操作系统,Linux和Window

-Dfile.encoding=UTF-8
Run Configuration → VM options里填写,不能只改文件编码设置java -jar命令后加上该参数:java -Dfile.encoding=UTF-8 -jar myapp.jar
IDE设置、文件实际编码、项目配置不一致是乱码高发区,尤其在团队协作中。
File → Settings → Editor → File Encodings,把Global Encoding、Project Encoding、Default encoding for properties files全部设为UTF-8
Preferences → General → Workspace → Text file encoding选Other: UTF-8,并勾选Always use encoding specified in the file
file -i filename.java(Linux/macOS)或Notepad++的编码菜单确认,避免BOM或ANSI残留任何涉及字节与字符串转换的API,只要没传编码参数,就等于埋雷。
Files.readAllLines(path, StandardCharsets.UTF_8),而非Files.readAllLines(path)
InputStreamReader(in, StandardCharsets.UTF_8),不用无参构造response.setCharacterEncoding("UTF-8"),且在getWriter()前设置ObjectMapper的setDefaultCharset(StandardCharsets.UTF_8)
最易被忽略的是Maven资源过滤和Spring Boot的application.properties加载——它们默认不识别UTF-8 BOM,含中文的properties文件必须保存为无BOM UTF-8,否则Spring会把开头的EF BB BF当乱码解析。