【发布时间】:2015-04-26 14:10:04
【问题描述】:
我已经阅读了 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 范围内写入任何字符,例如但不限于 áéíóúñ。在这些情况下,我会得到 missing character squares。我尝试使用其他编码无济于事。
更新:
一些具体问题:
为什么不在
InputStreamReader的构造函数中指定字符集使其正确解码多字节字符。InputStreams 有时会收到超过一个字节的字符。他们如何识别和处理这些字符。
更新 2:
我完全忘记了这段代码:
@Override
public void write(int b) throws IOException {
display.append(Character.toString((char) b));
}
这是造成麻烦的原因。我会正确地重写它,并期望没有进一步的编码/解码问题。
【问题讨论】:
-
把
BlockingQueue<Integer>改成BlockingQueue<Character> -
必须转换为字节才能使用
InputStream.read(),那时我将再次面临同样的问题! (我认为...)
标签: java unicode encoding inputstream bufferedreader