2

I was practicing using byte streams in Java when I came across this code:

import java.io.*;
public class CopyBytes_practice {
public static void main(String args[]) throws IOException {
    FileInputStream f=null;
    FileOutputStream fo=null;
    int c;
    int d;
    try {
        f=new FileInputStream("a.png");
        fo=new FileOutputStream("b.png");
        c=f.read();
        while(c != -1){
            fo.write(c);
        }
    } finally {
        if (f != null) {
            f.close();
        }
        if (fo != null) {
            fo.close();
        }
    }
}

I used a 35kb a.png file and a 0kb b.png file to execute the code, but the code ran forever - the size of b.png reached 905mb before I stopped the JVM manually.

I am confused, why is the end of file status not returned? Is it not supported in Binary files, or is something else wrong?

2 Answers 2

4

You missed something important

c=f.read(); // <-- Read in one byte ...
while(c != -1){
  fo.write(c);
  c=f.read(); // <--- Add this, to Read in the next byte (or -1)...
}

So you were infinitely looping, and writing the first byte from your source.

Sign up to request clarification or add additional context in comments.

3 Comments

That solved it... but i don't get it, can you please explain what c=f.read(); did???
You were reading only the first byte of your source file and writing it forever. It'd never be "-1" so it wouldn't ever stop. Calling c=f.read keeps going further on the source file till its end.
ohk, i get it now, that means writing while((c=f.read()) != -1) could have made my day, ryt? thanks :)
4

Yes, because it's an infinite loop, you need to tell the loop where to stop.In other words, the loop should keep reading until it reaches the end of the file.

 while ((c= f.read()) != -1){
    fo.write(c);
 }

1 Comment

because c was still equal to the first byte value, read() returns -1 when it reaches the end of the file. Every time you call read(), it jumps to the next chunk @user2869389

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.