【问题标题】:BufferedWriter not writing String CorrectlyBufferedWriter 未正确写入字符串
【发布时间】:2014-11-07 16:14:49
【问题描述】:

所以我有一个通过 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 

【问题讨论】:

    标签: java character-encoding bufferedwriter


    【解决方案1】:

    无论出于何种原因,您的文本编辑器都设置为显示底层字节的十六进制表示。您必须将其更改为以适当的字符集显示文本表示。

    例如

    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 个字符)。

    【讨论】:

    • 我编辑了我的文本编辑器(Sublime Text 2)不显示十六进制。我认为我可能做错了什么,因为 ST2 和 Windows 记事本都显示了十六进制
    猜你喜欢
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    相关资源
    最近更新 更多