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:

    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: