java中的read(byte【】)方法的问题

为什么is=system.in就会成为死循环,而上面用file程序就会停止图片说明

你用System.in时因为在while要检查输入的内容长度,因此会进入阻塞状态。不能说是死循环,循环的话会输出内容的,这里是阻塞了。

你输入了一次,会输出至少一次,根据你输入的内容长度来定,输出完毕后,会再次进入while判断条件中判断是否有新的输入,也就是说用System.in是没有办法达到一个普通文件那样的输入结尾的,只要你程序开着,他就可以一直输入。在read方法中它其实调用了read(byte b[], int off, int len)方法,该方法的注释中明确了会进入阻塞状态的条件,这里的len是你的byte数组长度为8,不为0.见下面加黑部分:

Reads up to len bytes of data from this input stream into an array of bytes. **If len is not zero, the method blocks until some input is available**; otherwise, no bytes are read and 0 is returned.

目测是readnext

system.in 是指从键盘输入的接收流,你没有输入,当然挂在那里,而不是什么死循环。

应该是这样写:
File f = new File(“E:\1.txt”);

InputStream in = new FileInputStream(f);

这样才能把文件 读进来

system.in 是指从键盘输入的接收流,你没有输入,当然挂在那里,而不是什么死循环。