【问题标题】:Java - Input/OutputStream between System.in and System.out - problem with readUTF() and writeUTF()Java - System.in 和 System.out 之间的输入/输出流 - readUTF() 和 writeUTF() 的问题
【发布时间】:2023-01-20 20:06:28
【问题描述】:

我正在尝试在 Java 中的 System.in 和 System.out 之间建立一个非常简单的通信流,以了解流的工作原理。 我为 System.in 使用 DataInputStream,为 System.out 使用 DataOutputStream,它们通过 readChar()、writeChar() 等进行通信。

一切似乎都工作正常,直到达到 readUTF() 为止:

DataInputStream dis = new DataInputStream(System.in);
DataOutputStream dos = new DataOutputStream(System.out);
        
try {
  char c = dis.readChar();
  dos.writeChar(c);
            
  int i = dis.readInt();
  dos.writeInt(i);
            
  String s = dis.readUTF();
  dos.writeUTF(s);
} catch (IOException e) {
  e.printStackTrace();
}       
try {
  dis.close();
  dos.close();
} catch (IOException e) {
  e.printStackTrace();
}   

控制台显示:

m /* note: keyboard input */
m
569
569
Hello

看起来我找不到指示字符串结尾的方法,没有考虑返回,也没有考虑 \n 等。我也尝试添加 " 但相同。

我遇到了另一个问题,这段代码没有在控制台中显示任何内容:

DataInputStream dis = new DataInputStream(System.in);
DataOutputStream dos = new DataOutputStream(System.out);
        
try {
  dos.writeUTF("Hello");
} catch (IOException e) {
  e.printStackTrace();
}       
try {
  dis.close();
  dos.close();
} catch (IOException e) {
 e.printStackTrace();
}

我试过添加 dos.flush() 但没有任何变化。 我想我误会了什么。

【问题讨论】:

标签: java inputstream outputstream datainputstream dataoutputstream


【解决方案1】:

您可能不应该使用 DataInputStreamDataOutputStreamreadUTFwriteUTF 使用非常特殊的序列化格式,其中文本以长度指示符为前缀,并使用修改后的 UTF8。控制台输入不使用这种格式,所以你输入的前 4 个字符用于计算长度,而你没有输入那么多字符,输出时用于字符串长度的 4 个字节可能会产生垃圾(如果包含生成修改格式的代码点,修改后的 UTF8 的使用也是如此)。您可能应该改用BufferedReaderScanner,直接使用System.out,或使用通过System.console()获得的Console

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 2012-05-16
    相关资源
    最近更新 更多