Search code examples
javaiofileinputstreamfileoutputstream

java read / write construction


Can someone explain me why this construction wont work:

while (fileInputStream.available()>0) {    
    fileOutputStream.write(fileInputStream.read());
}

and this one works just fine:

while (fileInputStream.available()>0) {
    int data = fileInputStream.read();
    fileOutputStream.write(data);
}

As for me they are identical, but 1st one wont write data correctly (will write half of file lenght / data).


Solution

  • You are using the available() method incorrectly. The method is used to determine how many bytes are available to be read without blocking the thread.

    Good Stack Overflow Question about available()

    JavaDoc on available()


    The correct way to check if you have reached the EOF is to see if the read() method returned -1:

    int data = fileInputStream.read();
    while (data != -1) {
        fileOutputStream.write(data);
        data = fileInputStream.read();
    }
    

    This method is probably going to be quite slow if you try to read in larger amounts of data. You can speed this up by reading in more bytes using the read(byte[] b, int off, int len) method. The loop will look quite similar to the other one.

    byte [] buffer = new byte[1024]; // 1kb buffer
    int numBytesRead = fileInputStream.read(buffer);
    while (numBytesRead != -1) {
        fileOutputStream.write(buffer, 0, numBytesRead);
        numBytesRead = fileInputStream.read(buffer);
    }