我正在努力让 Eclipse 正确读取中文字符,而且我不确定我可能哪里出错了。
具体来说,在从控制台读取一串中文(简体或繁体)和输出之间的某个地方,它会出现乱码。即使在输出一大串混合文本(英文/中文字符)时,它似乎也只会改变中文字符的外观。
我已将其缩减为以下测试示例,并用我认为在每个阶段发生的事情明确注释它 - 请注意,我是一名学生,非常想确认我的理解(或其他):)
public static void main(String[] args) {
try
{
boolean isRunning = true;
//Raw flow of input data from the console
InputStream inputStream = System.in;
//Allows you to read the stream, using either the default character encoding, else the specified encoding;
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
//Adds functionality for converting the stream being read in, into Strings(?)
BufferedReader input_BufferedReader = new BufferedReader(inputStreamReader);
//Raw flow of outputdata to the console
OutputStream outputStream = System.out;
//Write a stream, from a given bit of text
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
//Adds functionality to the base ability to write to a stream
BufferedWriter output_BufferedWriter = new BufferedWriter(outputStreamWriter);
while(isRunning) {
System.out.println();//force extra newline
System.out.print("> ");
//To read in a line of text (as a String):
String userInput_asString = input_BufferedReader.readLine();
//To output a line of text:
String outputToUser_fromString_englishFromCode = "foo"; //outputs correctly
output_BufferedWriter.write(outputToUser_fromString_englishFromCode);
output_BufferedWriter.flush();
System.out.println();//force extra newline
String outputToUser_fromString_ChineseFromCode = "之謂甚"; //outputs correctly
output_BufferedWriter.write(outputToUser_fromString_ChineseFromCode);
output_BufferedWriter.flush();
System.out.println();//force extra newline
String outputToUser_fromString_userSupplied = userInput_asString; //outputs correctly when given English text, garbled when given Chinese text
output_BufferedWriter.write(outputToUser_fromString_userSupplied);
output_BufferedWriter.flush();
System.out.println();//force extra newline
}
}
catch (Exception e) {
// TODO: handle exception
}
}
样本输出:
> 之謂甚
foo
之謂甚
之謂甚
> oaea
foo
之謂甚
oaea
> mixed input - English: fubar; Chinese: 之謂甚;
foo
之謂甚
mixed input - English: fubar; Chinese: 之謂甚;
>
在这篇 Stack Overflow 帖子上看到的内容与我在 Eclipse 控制台中看到的内容以及在 Eclipse 调试器中看到的内容完全一致(查看/编辑变量值时)。通过 Eclipse 调试器手动更改变量值会导致代码取决于该值的行为,就像我通常期望的那样,这表明文本是如何读取IN是一个问题。
我尝试了许多不同的扫描仪/缓冲流 [reader|writer] 等组合来读入和输出,无论是否有明确的字符类型,尽管这不是特别系统地完成的,而且很容易错过一些东西。
我已尝试将 Eclipse 环境设置为尽可能使用 UTF-8,但我想我可能错过了一两个地方。请注意,控制台将正确输出硬编码的汉字。
非常感谢您对此事的任何帮助/指导:)