2

I wrote this program to copy one pdf file to other but I'm getting curupt fiel in o/p for .txt files this code is working fine.

code:

public class FileCopy {

    public static void main(String args[]) {

        try {
            FileInputStream fs = new FileInputStream("C:\\dev1.pdf");
            byte b;
            FileOutputStream os = new FileOutputStream("C:\\dev2.pdf");
            while ((b = (byte) fs.read()) != -1) {
                os.write(b);
            }
            os.close();
            fs.close();
        } catch (Exception E) {
            E.printStackTrace();
        }
    }
}
1
  • I guess the problem is that I'm reading the data byte by byte , because when I'm using read(byte []) method the code is working fine. Commented Dec 18, 2012 at 13:12

2 Answers 2

4

It's because you are mixing ints and bytes. This should work as expected:

int b;
while ((b = fs.read()) != -1) {
    os.write(b);
}

In particular, when fs.read() returns 255, (byte) fs.read returns -1.

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

Comments

3

try this

try {          
   FileInputStream fs = new FileInputStream("C:\\dev1.pdf");

   FileOutputStream os = new FileOutputStream("C:\\dev2.pdf");
   while ((int b = (byte) fs.read()) != -1) {
       os.write(b);
   }
   os.close();
   fs.close();
} catch (Exception E) {
    E.printStackTrace();
}

1 Comment

This is a good answer though. try to add some explanation to your answer in future.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.