我正在尝试为我编写的一个小回显服务器接收日语字符。问题是,当我从 System.in 获取字符时(通过任何东西,扫描仪,InputStream,凡是你能想到的)它们总是作为垃圾进来的。我什至尝试使用
message = new String(bufferedReader.readLine().getBytes("UTF8");
为了尝试让字节以 Unicode 形式输入。
当我从服务器打印消息ようこそ(日语欢迎)时,它显示正常,问题仅在接受用户输入时存在。
控制台设置为在 Eclipse 中使用 UTF8。
这是我编写的一个小测试程序,以确保它是来自 System.in 的输入
输入和输出是
よ
よ
这是代码
public class TestUnicode {
public static void main(String[] args) throws IOException
{
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in, "UTF8"));
String message = stdIn.readLine();
System.out.println(message);
}
}
public class Client {
public static void main(String[] args) throws IOException
{
Socket serverSocket = null;
try
{
serverSocket = new Socket("192.168.1.127", 3000); //connect to myself at port 3000
}
catch(IOException e)
{
System.out.println(e);
System.exit(1);
}
BufferedReader in = null;
PrintStream out = null;
try //create in and out to write and read from echo
{
in = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
out = new PrintStream(serverSocket.getOutputStream(), true);
}
catch(IOException e)
{
serverSocket.close();
System.out.println(e);
System.exit(1);
}
String message = null;
message = in.readLine();
System.out.println(message); //print out the welcome message
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
//create a new buffered reader from my input
try
{
while(true)
{
message = bufferedReader.readLine();
out.println(message); //send a line to the server
if(message.equals("quit"))
{
System.out.println(in.readLine());
break;
}
System.out.println(in.readLine()); //get it back and print it
}
System.out.println("Quiting client...");
}
catch(IOException e)
{
in.close();
out.close();
serverSocket.close();
System.out.println(e);
System.exit(1);
}
in.close();
out.close();
serverSocket.close();
}
}
最佳答案
我假设您使用的是 Windows。
这里的问题是,DOS 提示符使用与 UTF-8 完全不同的字符编码。如果是日语,则为 Shift-JIS,因此尝试使用 UTF-8 InputStream
读取该内容是行不通的。
幸运的是,还有希望。您可以(并且应该)使用 System.console()
,而不是使用 System.in
。它将返回 Console class 的实例进行有效的字符编码转换。但是,您必须注意,尝试在 IDE(尤其是 Eclipse)之外调试它是行不通的,因为它不附加 Console。哎呀。
更正后的代码(我确信可以工作,但我还没有测试过):
public class TestUnicode {
public static void main(String[] args) throws IOException
{
Console console = System.console();
String message = console.readLine();
console.writer().println(message);
}
请注意,您还需要使用控制台
来打印消息。为什么?这只是因为您需要双向转换字符编码。 DOS 提示符仍然保留在旧编码中,并且无法更改。
关于java - 从 Java 中的 System.in 获取日语或中文输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18820401/