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?

1
  • 1
    Do not forget to flush the stream.
    – rodrigoap
    Dec 18, 2015 at 12:14

3 Answers 3

3

FileWriter fooWriter = new FileWriter(myFoo, false);

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

See this link

0
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

2
  • Will this also provide me with a file or do I have to create it first? Dec 18, 2015 at 12:28
  • all included. no need of supplementary file Dec 18, 2015 at 12:53
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

2
  • 1
    The English third-person pronoun is "you", not "u".
    – ArtOfCode
    Dec 18, 2015 at 12:38
  • @ArtOfCode Nice catch, I oversaw that while editing. Dec 18, 2015 at 13:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.