为什么我们在以下代码中使用-1?

时间:2013-11-09 11:11:06

标签: java fileinputstream

请解释我们在循环中使用-1的原因

<%  
    File file = new File(file1);       
    int ch;       
    strContent = new StringBuffer("");       
    FileInputStream fin = null;       
    try {       
        fin = new FileInputStream(file);       
        while ((ch = fin.read()) != -1) 
            strContent.append((char) ch);
        fin.close();
    } catch (Exception e) {
        System.out.println(e);
    }   
    System.out.println(strContent.toString());

%> 

在上面的代码中解释了为什么我们使用-1,我不明白为什么我们使用-1

5 个答案:

答案 0 :(得分:2)

read的文档:

  

返回:读入缓冲区的总字节数,如果由于文件末尾已到达而没有其他数据,则返回-1。

因此,当没有其他内容可供阅读时,循环结束

答案 1 :(得分:1)

你应该read doc:

  

如果到达文件末尾,方法read()将返回-1。

因此,当您到达文件末尾时,您希望停止while循环。

答案 2 :(得分:0)

此条件检查EOF(文件结束)。这是停止阅读一次,达到文件结束。

答案 3 :(得分:0)

这在Java文档中详细说明:

  

返回:   读入缓冲区的总字节数,如果由于已到达流末尾而没有更多数据,则为-1。

在这里阅读更多内容:

http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html

答案 4 :(得分:0)

public int read()
         throws IOException
  

从此输入流中读取一个字节的数据。如果没有,此方法会阻止   输入仍然可用。

指定者:

read in class InputStream

<强>返回:

  

下一个数据字节,如果到达文件末尾则为-1。

<强>抛出:

IOException - if an I/O error occurs.
相关问题