PrintStream 无法正确打印 unicode 字符 (UTF-16) [英] PrintStream doesn't print correctly unicode characters ( UTF-16)

查看:112
本文介绍了PrintStream 无法正确打印 unicode 字符 (UTF-16)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想正确打印 unicode(比如说希腊字符),但我遇到了问题.例如:

I want to print correctly unicode (let's say greek characters ) but I have problems. For example :

PrintStream oStream = new PrintStream(client.getOutputStream(), true, "UTF-8");
oStream.write(" Customer    : Γειά σου\r\n".getBytes());
oStream.write(" ΚΩΔΙΚΟΣ     : 00000234242\r\n".getBytes());
oStream.flush();
oStream.close();

                             OR
 OutputStreamWriter oStream = new OutputStreamWriter(client.getOutputStream(), "UTF-16");
    oStream.write(" Customer    : Γειά σου\r\n");
oStream.write(" ΚΩΔΙΚΟΣ     : 00000234242\r\n");
oStream.flush();
oStream.close();

问题是是否有任何解决方案可以正确打印所有字符.我认为对于希腊字符 UTF-16 是可以的.

The question is if there is any solution to print correctly all of the caharacters. I think for Greek characters UTF-16 is ok.

推荐答案

这很可能是问题所在:

oStream.write(" Customer    : Γειά σου\r\n".getBytes());
oStream.write(" ΚΩΔΙΚΟΣ     : 00000234242\r\n".getBytes());

您正在调用没有编码的 String.getBytes(),以使用平台默认编码获取字节数组.无论如何,这几乎总是一个坏主意,这意味着您之前指定的 UTF-8 与这两行无关.到 PrintStream 获取数据时,它已经是二进制的了.

You're calling String.getBytes() with no encoding, to get a byte array using the platform default encoding. That's almost always a bad idea anyway, and it means that the fact that you specified UTF-8 earlier is irrelevant to these two lines. By the time the PrintStream gets the data, it's already in binary.

试试这个:

oStream.print(" Customer    : Γειά σου\r\n");
oStream.print(" ΚΩΔΙΚΟΣ     : 00000234242\r\n");

注意事项:

  • 我建议不要使用 PrintStreamPrintWriter.他们吞下了例外.
  • 如果你只写文本,你应该使用 Writer 子类而不是 OutputStream 子类
  • 不清楚您的源代码是否得到正确处理:您需要检查用于编译代码的任何内容是否知道您的源文件使用的是什么编码.
  • I would advise against using either PrintStream or PrintWriter. They swallow exceptions.
  • If you're only writing text, you should use a Writer subclass rather than an OutputStream subclass
  • It's unclear whether your source code is even being handled correctly: you need to check that whatever you're using to compile your code knows what encoding your source file is using.

我建议您将输出流包装在 OutputStreamWriter... 中,这将允许您指定编码,您不必担心意外写入二进制数据(因为 API 没有)t 允许它)并且您不会看到异常被吞下.

I suggest you wrap your output stream in an OutputStreamWriter... that will allow you to specify the encoding, you won't have to worry about accidentally writing binary data (as the API doesn't allow it) and you won't see exceptions getting swallowed.

这篇关于PrintStream 无法正确打印 unicode 字符 (UTF-16)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆