Search code examples
javafileinputstream

FileInputStream; Why can FileInputStream become an integer, does it have any meaning?


I'm studying java in a certain website and I found this

 import java.io.*;
public class CopyFile {

   public static void main(String args[]) throws IOException {  
      FileInputStream in = null;
      FileOutputStream out = null;

      try {
         in = new FileInputStream("input.txt");
         out = new FileOutputStream("output.txt");

         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}

What is the meaning of c = in.read()) != -1?Why can it be an integer?


Solution

  • Your FileInputStream is a stream of bytes.

    When you call FileInputStream.read() it return a byte from the stream or return -1 if reach end of stream.

    When you write: c = in.read()) != -1,

    • a byte is read from stream, widening as int, assign back to c and
    • a check is made to see if a byte is read successfully by comparing the returned value with -1;