Copying a file from a location to another location

I am trying to read a file and write it to a specific folder. I am using this code:

private void saveFile(File file){
    try {
        OutputStream out = new FileOutputStream(new File("/Users/default/Desktop/fotos/test.png"));
        Files.copy(file.toPath(), out);
                System.exit(0);

    } catch (IOException ex) {
        Logger.getLogger(GetFiles.class.getName()).log(Level.SEVERE, null, ex);
    }
}

The file is a .png file. If I use this method it will create a new .png in the fotos directory, but when I double click it it says that it's empty. How is this possible and how can I solve this?

Jon Skeet
people
quotationmark

You're not closing the output stream. Therefore any data buffered within it before being written out to disk will be lost.

You could use a try-with-resources statement to close the stream automatically - or you could just use:

// Alternatives, pass in the `File` to copy to, or make the method generally
// more flexible in other ways.
Files.copy(file.toPath(), Paths.get("/Users/default/Desktop/fotos/test.png"));

As an aside, it's unusual to call System.exit in a method like this - it's not like the method is saveFileAndTerminateApplication. Likewise your exception "handling" isn't ideal. I would basically let the exception bubble up, i.e. declare that your method throws it. Currently, there are three possibilities:

  • Everything works, and the app terminates
  • The copy works, but System.exit throws an unchecked exception
  • The copy fails, so the method returns - the caller could infer that something went wrong, but with no idea what

That doesn't sound like an obvious set of results to me...

people

See more on this question at Stackoverflow