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");
}
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:
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:
close()
is in the finally
block, close()
will be called after successfully writing to the file but also if anything goes wrong.close()
call is added for you implicitly so you have one thing less to think about.