BufferedWriter没有正确编写String

时间:2014-11-07 16:14:49

标签: java character-encoding bufferedwriter

所以我有一个通过telnet与数据库通信的程序,之前我已将它打印到控制台System.out.println()。现在我正在修改我的程序,以便将响应写入文件,以便我可以将程序作为服务/守护程序运行。但是,当使用BufferedWriter时,我不会说英语。文件资源管理器中的文件预览正确读取但是当我在记事本或Sublime Text 2中打开文件时,我得到了这个奇怪的数字组合。这是我的代码和文件应该说的内容,而不是我打开文件时得到的内容。

private static void logon() throws IOException {
    bout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/mnt/javaprograms/ServerConsole/log.txt"), "UTF-8"));

    String loginString = "JAVA-TRANS\n";
    byte[] logon = loginString.getBytes();
    out.write(logon);
    out.flush();
    out.write(logon);
    out.flush();
    response = in.readLine();
    bout.write(response);
    bout.flush();
    while (!response.contains("OK")) {
        response = in.readLine();
        bout.write(response);
        bout.flush();
    }
    bout.flush();
    bout.close();
}

文件资源管理器预览:

  

欢迎使用mvBASE telnet服务器。您已连接到第54行   MILL6JAVA-TRANS

打开的文件读取:

5765 6c63 6f6d 6520 746f 2074 6865 206d
7642 4153 4520 7465 6c6e 6574 2073 6572
7665 722e 596f 7520 6172 6520 636f 6e6e
6563 7465 6420 746f 206c 696e 6520 3534
206f 6e20 4d49 4c4c 364a 4156 412d 5452
414e 5300 4f4b 

1 个答案:

答案 0 :(得分:0)

无论出于何种原因,您的文本编辑器都会设置为显示基础字节的十六进制表示。您必须更改它以在相应的字符集中显示文本表示。

例如

public static void main(String[] args) throws Exception {
    String text = "Welcome to the mvBASE telnet server.You are connected to line 54 on MILL6JAVA-TRANS";
    byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
    int space = 0;
    for (byte b : bytes) {
        System.out.print(Integer.toHexString(b));
        space++;
        if (space == 16) {
            System.out.println();
            space = 0;
        } else if (space % 2 == 0) {
            System.out.print(" ");
        }
    }
}

打印

5765 6c63 6f6d 6520 746f 2074 6865 206d 
7642 4153 4520 7465 6c6e 6574 2073 6572 
7665 722e 596f 7520 6172 6520 636f 6e6e 
6563 7465 6420 746f 206c 696e 6520 3534 
206f 6e20 4d49 4c4c 364a 4156 412d 5452 
414e 53

你看到的是什么(+/- 3个字符)。

相关问题