2

I am trying to copy a PDF file from 1 location to another, but once I run the following code, I am unable to open the PDF (it is showing the following error.)

There was an error opening this document. The file is damaged and could not be repaired

public class BinaryFileTransfer {

    private static String INPUT_FILE = "C:\\Users\\sashwat\\Desktop\\a.pdf";
    private static String OUTPUT_FILE = "C:\\Users\\sashwat\\Desktop\\a-copy.pdf";

    public static void main(String args[]) throws Exception {
        InputStream is = new BufferedInputStream(new FileInputStream(INPUT_FILE));

        OutputStream wos = new BufferedOutputStream(new FileOutputStream(OUTPUT_FILE));

        int len = 0;
        byte[] brr = new byte[1000];
        while ((len = is.read(brr)) != -1) {
            wos.write(brr, 0, len);
        }
    }
}

Can someone help me as to what exactly am I doing wrong?

Keen Sage
  • 1,799
  • 4
  • 21
  • 39

1 Answers1

3

The problem here is that you're not closing the input / output streams. This is a resource leak and I reproduced your problem on a Windows machine.

Starting with Java 7, you can use the try-with-resources statement to do that automatically:

public static void main(String[] args) throws IOException {
    try (InputStream is = new BufferedInputStream(new FileInputStream(INPUT_FILE));
        OutputStream wos = new BufferedOutputStream(new FileOutputStream(OUTPUT_FILE))) {
        int len = 0;
        byte[] brr = new byte[1000];
        while ((len = is.read(brr)) != -1) {
            wos.write(brr, 0, len);
        }
    }
}

At the end of the try part, each resource opened will be closed.

However, I strongly suggest that you start using the Java NIO.2 API. You can copy a file directly with Files.copy.

Files.copy(Paths.get(INPUT_FILE), Paths.get(OUTPUT_FILE));

It can also take a 3rd argument that are CopyOption. An example could be StandardCopyOption.REPLACE_EXISTING which replaces the target file if it already exists.

Tunaki
  • 116,530
  • 39
  • 281
  • 370