ard*_*rus 2 java input stream return-value
我写了一个简单的程序来测试read()方法,我注意到我读取的字节数的值与预期的不同.这是程序:
class ReadBytes {
public static void main(String[] args) throws java.io.IOException {
byte[] data = new byte[10];
System.out.println("Read some characters.");
System.out.println("You have read " + System.in.read(data) + " bytes.");
System.out.print("You wrote: ");
for(int i = 0; i < data.length; i++) {
System.out.print((char) data[i]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题在于第二个println的输出.当我只按Enter键而不插入任何其他字符时,输出为:
读一些字符.
你已经阅读了2个字节.
你写了:
我期待" 你读过0个字节. "
事实上,对于我输入8的每个字符,我得到(字节预期+ 2),超过8个字符,我得到10的值.
有人能解释一下这些额外的2个字节的含义吗?
感谢您抽出时间阅读并帮助我.
当您按Enter键时,您的计算机将系统相关的行终止符/分隔符字符传递给输入流/控制台,让它知道您按下了回车键并且输入的行已准备好进行处理.您的输入流正在读取这些字符.
在Windows上,这些字符是"\r\n"
(回车符后跟换行符).对于*nix系统它是'\n'
唯一的,所以在Mac或Linux机器上你会看到"You have read 1 bytes."
我不确定是否可以实际读取0个字符.您可以关闭输入流,但这可能会导致类似NoSuchElementException
或类似的输入流.不确定CTRL + D和/或EOF会做什么.