Search code examples
javafilewriterprintwriter

Java Trying to write to files, with the names of the files being stored in an array. The files are being created when I run it, but nothing is in them


I have included skeleton code below. I'm sure it's just something simple, but I have no idea how to debug the printwriter and filewriter.

String[] outputs = {"output_1.txt", "output_2.txt"};
PrintWriter writer = null;
FileWriter file = null;

for(int i = 0; i < outputs.length; i++){

    file = new FileWriter(outputs[i]);
    writer = new PrintWriter(file);
    writer.println("write this to file");

}

Solution

  • As mentioned in the comments, you need to close the file when you are done writing to it. You can do that with writer.close(), however, this is not ideal for multiple reasons:

    • If something goes wrong while writing to the file (i.e. an exception is thrown) the function will exit prematurely and writer.close() will never be called. While this doesn't matter in this particular example, this can leave so-called dead-locks in bigger programs, which is never a good idea.
    • People are lazy and you will more often than not forget to call writer.close() the next time you have a similar task.

    Therefore, start making good habits now and use the following:

    try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(Paths.get(outputs[i])))) {
        writer.println("write this to file");
    }
    

    Under the hood, this does the following for you:

    PrintWriter writer = new PrintWriter(Files.newBufferedWriter(Paths.get(outputs[i])))
    try {
        writer.println("write this to file");
    } finally {
        writer.close()
    }
    

    which has the following advantages:

    • Because the call to close() is in the finally block, close() will be called after successfully writing to the file but also if anything goes wrong.
    • The close() call is added for you implicitly so you have one thing less to think about.