Append text to files using FileWriter | Community
Skip to main content
Level 3
May 31, 2023
Solved

Append text to files using FileWriter

  • May 31, 2023
  • 1 reply
  • 858 views

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!

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by Kiran_Vedantam

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.

1 reply

Kiran_Vedantam
Community Advisor
Kiran_VedantamCommunity AdvisorAccepted solution
Community Advisor
May 31, 2023

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.