gpt4 book ai didi

java - UTF 编码/解码后不打印重音

转载 作者:行者123 更新时间:2023-12-01 22:20:39 25 4
gpt4 key购买 nike

我已阅读 several articles总体topic我还是不明白这是怎么回事。请亲自查看以下工作示例(实际上,没有示例,这是我正在处理的完整类,添加了一些 main())。

public class Console extends JFrame {

private static final long serialVersionUID = 2260047176466126845L;
private static final String ENCODING = "UTF-8";

private BlockingQueue<Integer> inBuffer = new LinkedBlockingQueue<Integer>();
private JTextArea display = new JTextArea();
private JTextField input = new JTextField();
private ActionListener listener = new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Input: " + input.getText());
byte[] bytes = (input.getText() + "\n").getBytes(Charset.forName(ENCODING));
input.setText("");
System.out.println("Bytes: " + Arrays.toString(bytes));
for(byte b : bytes) {
inBuffer.offer((int) b);
}
}
};

public Console() {
super("Debugging");

LayoutManager layout = new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS);
setLayout(layout);
display.setPreferredSize(new Dimension(420, 210));
display.setEditable(false);
input.addActionListener(listener);
input.setPreferredSize(new Dimension(420, 20));
add(display);
add(input);
pack();
setVisible(true);
}

public final BufferedReader in = new BufferedReader(
new InputStreamReader(
new InputStream() {

boolean lastWasEnd = false;

@Override
public int read() throws IOException {
Integer c;
if(lastWasEnd) {
lastWasEnd = false;
return -1;
}

try {
c = inBuffer.poll(10, TimeUnit.MINUTES);
lastWasEnd = inBuffer.isEmpty();
return c;
} catch (InterruptedException e) {
e.printStackTrace();
}

return -1;
}
}, Charset.forName(ENCODING)
)
);

public final PrintStream out = new PrintStream(new OutputStream() {

@Override
public void write(int b) throws IOException {
display.append(Character.toString((char) b));
}

});

public static void main(String args[]) {
Console cons = new Console();
cons.out.println(">> Console started. Using charset: " + Charset.forName(ENCODING));
while(true) {
System.out.println("Loop");
try {
cons.out.println(">> " + cons.in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

一切都很顺利,直到我尝试编写超出标准 ASCII 范围的任何字符,例如但不限于 áéíóúñ。在这些情况下,我会得到缺少字符方 block 。我尝试过使用其他编码,但没有成功。

更新:

一些具体问题:

  1. 为什么在 InputStreamReader 的构造函数中指定字符集不能使其正确解码多字节字符。

  2. InputStream有时会接收超过一字节的字符。无论如何,他们如何识别和处理这些字符。

更新2:

我完全忘记了这段代码:

@Override
public void write(int b) throws IOException {
display.append(Character.toString((char) b));
}

这就是造成麻烦的原因。我会正确地重写它,并期望不再出现编码/解码问题。

最佳答案

UTF-8 是一种多字节编码。这意味着一个字符可能具有超过一个字节长的表示形式,特别是如果它不是 US-ASCII 类型的字符。由于不清楚的原因,您专门将字符串分解为字节,然后附加它们。因此,您将这些字符分解为单独的字节,然后将这些字节视为整个字符。

如果字符长度超过一个字节,这将不起作用。

考虑为什么您要尝试将单个字节而不是整个字符排入队列,如果没有充分的理由,则尝试不将字符串转换为字节而是字符。

关于java - UTF 编码/解码后不打印重音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com