????????Java中中文乱码的解决方案有很多种,以下是其中一些常见的方法:
String str = "你好,世界!";
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
// 读取文件时指定字符编码
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("file.txt"), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// 写入文件时指定字符编码
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("file.txt"), StandardCharsets.UTF_8))) {
writer.write("你好,世界!");
} catch (IOException e) {
e.printStackTrace();
}
String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8";
Connection conn = DriverManager.getConnection(url, "user", "password");
// 设置请求的字符编码为UTF-8
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>你好,世界!</h1>");
out.println("</body></html>");