【问题标题】:system.out redirection to jfx fextfield not showing scandinavian characterssystem.out 重定向到 jfxtextfield 不显示斯堪的纳维亚字符
【发布时间】:2015-12-08 11:18:40
【问题描述】:

这几天我一直在摸不着头脑,试图弄清楚如何正确编码斯堪的纳维亚字符以在文本字段中使用

这三个字符:Æ Ø Å ( æ ø å) 显示为 ���。 意思是运行这段代码

System.out.println("øst");

打印"�st" .我不知道为什么。

这是我将 System.out 重定向到打印流的代码。

System.setProperty("user.language", "da");
    OutputStream out = new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            appendConsole(new String(new byte[]{(byte)b}, "UTF-8"));
        }
    };
    PrintStream ps;
    try {
        ps = new PrintStream(out, true, "UTF-8");
        System.setOut(ps);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(GameController.class.getName()).log(Level.SEVERE, null, ex);
    }

如果有人能解决这个问题,不胜感激!

【问题讨论】:

    标签: java encoding byte outputstream printstream


    【解决方案1】:

    尽量不要将 int 转换为字节转换为字符串,而是转换为 char。这行得通吗?

    【讨论】:

    • 不,完全一样的结果,不幸的是:/
    • 这实际上是我开始的地方,转换为字节并使用字符串构造函数是我修复它的尝试:)
    • 摆脱这个new String(...);,这是非常资源化的(?):D 将您的特殊字符转换为 unicode 字符怎么样?例如ø 将转换为 \u00f8 (System.out.println("\u00f8st");)
    【解决方案2】:

    当这些字符被编码为 UTF-8 时,它们每个都需要两个字节。例如,UTF-8 中的Æ 是{ (byte) 0xc3, (byte) 0x86 }。您不能仅从一个字节构造字符串;这两个字节都是形成有效的 UTF-8 序列所必需的。

    您需要累积字节,直到有足够的空间形成完整的 UTF-8 序列,然后从中创建一个字符串。 ByteBuffer 和 CharsetDecoder 就是为此而生的:

    // A UTF-8 sequence for a single character is at most 4 bytes long.
    private final ByteBuffer buffer = ByteBuffer.allocate(4);
    
    private final CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
    
    @Override
    public void write(int b)
    throws IOException {
    
        buffer.put((byte) b);
    
        int size = buffer.position();
        int first = buffer.get(0) & 0xff;
        if (size == 4 ||
            (first >= 0xe0 && size == 3) ||
            (first >= 0xc0 && size == 2) ||
            first < 0x80) {
    
            buffer.flip();
            appendConsole(decoder.decode(buffer).toString());
            buffer.clear();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-14
      • 1970-01-01
      • 2016-04-10
      • 1970-01-01
      • 2018-11-14
      • 2014-11-03
      • 1970-01-01
      • 2014-06-10
      • 2011-04-17
      相关资源
      最近更新 更多