I want to open a file, write it in a loop (append everything to the previous lines) and then close it. I had already implmented everything in a single method inside the loop and I had a problem similar to this question. So, I'm trying to implement it according to the suggestion that writing and opening must be done in different steps. My code now is like the following:
PrintWriter out= createAndOpenFile(fileName);
for (int i = 0 ; i< test.size(); i++){
writeToFile(mystring, out);
}
out.close();
And the implementation of the above methods are like the following:
private PrintWriter createAndOpenFile(String fileName) {
try (FileWriter fw = new FileWriter(fileName);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)) {
return out;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private void writeToFile(String features, PrintWriter out) {
out.println(features);
out.flush();
}
Can anyone tell me what is wrong with my code?
Update: With "not working" I meant that the file is empty at the end, though created.