【发布时间】: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() 但没有任何变化。 我想我误会了什么。
【问题讨论】:
-
我认为 The readUTF() method of the DatainputStream, which reads the text data separately, will report an EOF exception. Why? 是一个很好的副本。另一个关于读取文件的问题并不重要,“readUTF”的作用很重要,并且在此处进行了解释。
标签: java inputstream outputstream datainputstream dataoutputstream