0

Wanna save some information that I parse from a JSON to a plain text into a file and I also want this information to not be overwritten every time you run the program. It's suppose to work as a simple error logging system.

So far have I tried this:

FileWriter fileWriter = null;
File file = new File("/home/anderssinho/bitbucket/dblp-article-analyzer/logg.txt");

// if file doesn't exists, then create it
if (!file.exists()) {
    file.createNewFile();
}

...

String content = "------------------------------------";
fileWriter = new FileWriter(file);
fileWriter.write(content);
//fileWriter.write(obj.getString("title"));
//fileWriter.write(obj.getString("creators"));
//fileWriter.write(article.GetElectronicEdition());

But when I do this it seems that I overwrite the information all the time and I'm also having problem to save the information I wanna grab from the JSON-array that I've got.

How can I do to make this work?

Ramesh-X
  • 4,853
  • 6
  • 46
  • 67
anderssinho
  • 298
  • 2
  • 7
  • 21

3 Answers3

3

FileWriter fooWriter = new FileWriter(myFoo, false);

// true to append
// false to overwrite; where myFoo is the File name

See this link

Community
  • 1
  • 1
optimus
  • 729
  • 2
  • 12
  • 36
2

use append:

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("logg.txt", true)));

see this: How to append text to an existing file in Java

Community
  • 1
  • 1
2

Can you be more elaborate on this? If the problem is just not able to append then you can just add an argument to the FileWriter saying it to append and not write from the beginning.

Check the constructor here:

public FileWriter(String fileName, boolean append) throws IOException

Official Java Documentation:

Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.

Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason

ArtOfCode
  • 5,702
  • 5
  • 37
  • 56
KD157
  • 763
  • 7
  • 16