我有一个可以在控制台上运行的程序,我想为其创建一个自定义控制台。当前的命令行界面可以使用将InputStream和PrintStream作为参数的方法来启动。
我有两个文本区域(JTextArea),其中一个我要用于输入,另一个要用于输出。我扩展了InputStream和OutputStreams来为我的启动方法提供流:
public class ConsoleInputStream extends InputStream implements KeyListener {
private BlockingDeque<Integer> mBuffer = new LinkedBlockingDeque<>();
private JTextArea mJTextArea;
public ConsoleInputStream(JTextArea JTextArea) {
mJTextArea = JTextArea;
mJTextArea.addKeyListener(this);
}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyChar();
char c = (char) key;
mBuffer.add(key);
}
@Override
public int read() {
try {
char c = (char) (int) mBuffer.take();
if(c == '\n')
mJTextArea.setText("");
return c;
} catch (InterruptedException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int read(byte[] b, int off, int len) {
if (b == null) {
throw new NullPointerException();
} else if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
int c = read();
if (c == -1) {
return -1;
}
b[off] = (byte)c;
int i = 1;
try {
for (; i < len && available() > 0 ; i++) {
c = read();
if (c == -1) {
break;
}
b[off + i] = (byte)c;
}
} catch (IOException e) {
}
return i;
}
}
对于输出:
public class ConsoleOutputStream extends OutputStream {
private JTextArea mJTextArea;
public ConsoleOutputStream(JTextArea JTextArea) {
mJTextArea = JTextArea;
}
@Override
public void write(int b) throws IOException {
mJTextArea.append(String.valueOf((char) b));
}
}
启动程序:
CommandInterface.get().start(ui.getConsoleIn(), new PrintStream(ui.getConsoleOut()));
(ui是扩展JFrame的类的实例,getConsoleIn()和getConsoleOut()返回ConsoleInputStream和ConsoleOutputStream的实例)
在其中我使用扫描仪读取输入流:
public void start(InputStream inputStream, PrintStream outputStream){
Scanner scanner = new Scanner(inputStream, "UTF-8");
while (true){
String[] input = scanner.nextLine().split(" ");
if(input[0].equals("exit"))
break;
Command command = mCommands.get(input[0]);
if(command == null){
displayErrorMessage("No such command", outputStream);
continue;
}
List<String> flags = new LinkedList<>();
List<String> params = new LinkedList<>();
for(String s : Arrays.copyOfRange(input, 1, input.length)){
if(s.charAt(0) == '/')
flags.add(s.substring(1));
else
params.add(s);
}
command.execute(outputStream, flags, params);
}
}
直到我尝试使用本地字符:śćóż等等,这都可以正常工作。
我尝试了许多不同的解决方案,但没有一个对我有用。然后我试图自己弄清楚。每次阅读char时,我也会将其打印到标准输出(我的IDE)上,我知道它可以正确显示这些字符。我发现它们被正确读取,但是其中有三个字符(UTF-8 65535)(不是规则模式而是成对出现),原因我不清楚。我也尝试过:
Scanner scanner = new Scanner(System.in);
while (true){
ui.getConsoleOut().write(scanner.nextLine().getBytes(StandardCharsets.UTF_8));
}
具有不同的字符集,但无法正确显示它们。
显示那些(和其他UTF-8)字符的正确方法是什么?