Expand my Community achievements bar.

SOLVED

Append text to files using FileWriter

Avatar

Level 3

I am trying to append new line of text for different json files. But for some reason, each json file only has one line after the below code is executed but it shouldn't. 

 

Node confNode = session.getNode("/etc");
Node reportFileNode;
Node contentNode;
for (int jIndex = 0; jIndex < array.length(); jIndex++){
String title= array.getJSONObject(jIndex).getString("title");
File file = File.createTempFile( title,".json");
FileWriter fw = new FileWriter(file, true);
fw.append(array.getJSONObject(jIndex).toString() + "\n");
fw.close();
if (confNode.hasNode( title+".json")) {
reportFileNode = confNode.getNode(title+ ".json");
contentNode = reportFileNode.getNode("jcr:content");
} else {
reportFileNode = confNode.addNode(title+".json", "nt:file");
contentNode = reportFileNode.addNode("jcr:content", "nt:unstructured");
}
FileInputStream fileInputStream = new FileInputStream(file);
Binary contentValue = session.getValueFactory().createBinary(fileInputStream);
contentNode.setProperty("jcr:data", contentValue);
}

 I already used "append" as well as adding "\n" to the file. Am I missing something? Thanks!

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

HI @aemUser2345 

 

As per your code, you are creating and closing the file in the same for loop. Hence it's saving the last instance of the text that you are wanting to append. Can you create the file before the for loop and close it once all the data storage is completed and try?

 

Hope it helps!

Thanks,
Kiran Vedantam.

View solution in original post

1 Reply

Avatar

Correct answer by
Community Advisor

HI @aemUser2345 

 

As per your code, you are creating and closing the file in the same for loop. Hence it's saving the last instance of the text that you are wanting to append. Can you create the file before the for loop and close it once all the data storage is completed and try?

 

Hope it helps!

Thanks,
Kiran Vedantam.