1

I was refreshing myself on I/O while I was going over the example code I saw something that confused me:

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

    FileInputStream in = null;
    FileOutputStream out = null;

    try {
        in = new FileInputStream("xanadu.txt");
        out = new FileOutputStream("outagain.txt");
        int c;

        while ((c = in.read()) != -1) {
            out.write(c);
        }

How can an int value (c), can be assigned to a byte of data from the input stream (in.read())? And what why does the while loop wait for it to not equal -1?

progyammer
  • 1,498
  • 3
  • 17
  • 29
14k.wizard
  • 41
  • 6

2 Answers2

2

This (c = in.read()) will return -1 when the end of input is reached and hence the while loop will stop.

Read this awesome answer.

From Oracle docs:

public abstract int read() throws IOException Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown. A subclass must provide an implementation of this method.

Returns: the next byte of data, or -1 if the end of the stream is reached. Throws: IOException - if an I/O error occurs.

Community
  • 1
  • 1
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
0

From the documentation for FileInputStream.read():

public int read() throws IOException

Thus read() returns ints, not bytes, so it can be assigned to an int variable. Note that ints can be implicitly converted to ints with no loss. Also from the docs:

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

The loop check against -1 determines whether the end of file has been reached, and stops looping if so.

ABCRic
  • 36
  • 3