Java

java乱码怎么转中文

小亿
172
2024-06-05 09:56:16
栏目: 编程语言

在Java中处理乱码问题可以通过以下方式转换乱码为中文:

  1. 使用String的getBytes方法将乱码字符串转换为字节数组,然后通过指定正确的字符集进行解码,例如:
String str = "乱码字符串";
byte[] bytes = str.getBytes("ISO-8859-1");
String chineseStr = new String(bytes, "UTF-8");
System.out.println(chineseStr);
  1. 使用InputStreamReader将InputStream中的乱码数据转换为正确的字符编码,例如:
InputStream inputStream = new FileInputStream("乱码文件.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
    System.out.println(line);
}

以上是两种常见的处理乱码问题的方法,根据具体情况选择适合的方法进行转换。

0
看了该问题的人还看了