0

This code will add text to new line but is there a way to write to the last line of the file?

try (FileWriter fileWriter = new FileWriter(file)) {               
   fileWriter.append("{\"receivedtime\":\""+dateReceived+"\", " + "\"text\":\""+text+"\"}");
   fileWriter.flush();
}

As you can see I am writing JSON file with java. But there is this comma issue at the end of the line if there is another line. So I thought if I had a new line I will add the comma then the \n then the line. For the last line I don't need the comma so just the end ]}

{"employees":[
  {"firstName":"Anna", "lastName":"Smith"},
  {"firstName":"Peter", "lastName":"Jones"} 
]}
Charly Roch
  • 368
  • 1
  • 4
  • 15
  • 1
    Take another look at the constructors for FileWriter: http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html – ControlAltDel Jun 21 '16 at 15:46
  • what is the problem exactly? – Nicolas Filotto Jun 21 '16 at 15:47
  • 1
    OP is trying to alter the last line in a file by appending to the last line. But it appears using `FileWriter.append()` may be putting it on a new line below the last line, which is not what OP wants. – Clark Kent Jun 21 '16 at 15:49
  • Oh well nevermind. I knew this argument but thought it was writing a new line at the end. I am surprise that it doesn't. Might be weird but I am sure it wasn't working few weeks ago that's why I didn't try with this today. I was wrong. Thank's all. – Charly Roch Jun 21 '16 at 15:54
  • @ClarkKent yes that's exactly what's happening there, just needed to put the FileWriter fileWriter = new FileWriter(file,true) to be at the last line. And I am quite sure without the true it supposed to erase the file not writing a new line at the end. :/ Anyway it works. – Charly Roch Jun 21 '16 at 16:02

0 Answers0