JAVA字节流读磁盘文件问题

代码如下:package 练习2;import java.io.*;public class Main { public static void main(String[] args) throws IOException { int ch; File file1=new File("D:\\文件用\\JAVA练习\\newFile.txt"); try{ FileInputStream fin=new FileInputStream(file1); System.out.println("文件信息为:"); ch=fin.read(); while(ch!=-1) { System.out.print((char)ch); ch=fin.read(); } fin.close(); } catch(FileNotFoundException e) { System.out.println(e); } catch(IOException e) { System.out.println(e); } }} 我想问 为什么 ch要!=-1呢? 就是那个 while(ch!=-1)还有希望有人能给商 那些异常 入 IOException 等的中文解析给我 我加分!!!

第1个回答  2012-03-06
当ch等于-1时,说明在这个文件流中,内容已经读取完了。至于这个-1么,是调用这个read()函数时那个类中定义的。
throws IOException :这个是将异常抛给java虚拟机处理。
FileNotFoundException:文件是否找到的异常;
IOException:这个异常处理(输入输出异常类)的范围很大,你可以直接套用这个异常处理,但是当异常出现时,就有点难找了。
第2个回答  2012-03-06
public int read()方法是读下一个数据字节;如果已到达文件末尾,则返回 -1。当ch=-1时表示文件读完。 个人建议,如果文件传送,或者io流读取文件为空的时候建议,先读取文件出文件长度,通过文件长度来判断是否读取完。 仅供参考。
第3个回答  2012-03-06
这是FileInputStream的read方法,当返回-1时表示文件已经读完了,所以在!=-1的时候要继续读取文件
===================================
/**
* Reads a byte of data from this input stream. This method blocks
* if no input is yet available.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* file is reached.
* @exception IOException if an I/O error occurs.
*/
public native int read() throws IOException;本回答被提问者采纳
第4个回答  2012-03-06
一个文件的信息并不是你看见的这么少而已,还有其他的。
第5个回答  2012-03-06
做任务请无视
相似回答