Search code examples
javafilefileinputstream

what is the variable "data" storing in this java program?


My code is working. I just need to know about the role of a specific variable in the code.

I tried to print the value in the variable "data", but it gives me some numbers i cant understand.

public static void main(String[] args) throws IOException {

    FileInputStream fileinputstream = new FileInputStream ("c:\\Users\\USER\\Desktop\\read.TXT");

    FileOutputStream fileoutputstream = new FileOutputStream("c:\\Users\\USER\\Desktop\\write.TXT");

    while (fileinputstream.available() > 0) {
        int data = fileinputstream.read();                                                       
        fileoutputstream.write(data);
    }

    fileinputstream.close();
    fileoutputstream.close();
}

Solution

  • You can look at the docs for FileInputStream.read, which says:

    Reads a byte of data from this input stream. This method blocks if no input is yet available.

    Returns:

    the next byte of data, or -1 if the end of the file is reached.

    So the integer you got (i.e. the number stored in data) is the byte read from the file. Since your file is a text file, it is the ASCII value of the characters in that file (assuming your file is encoded in ASCII).