2

I have a code that should write lines in File.. - If file don't exist, it should make new file with that name. - If file exist, it should just write new line...

It appears that it always make new file and i cant figure out how to avoid it... Here is my code...

How to make it just to write new line if file is already there?

Thx for ur time...

if (isANumber(value) == true) {
    String valResult = "validation_result=VALID";
    BufferedWriter writer = null;
    writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("ValidationResults.txt")));
    System.out.println("Writing in TEXT file: " + "type=" + key + ";value=" +  value + ";" + valResult);
    writer.newLine();
    writer.write("\ntype=" + key + ";value=" +  value +  valResult + "\n");
    writer.flush();
    writer.close();
} else {
    valResult = "validation_result=INVALID";
    BufferedWriter writer =  new BufferedWriter(new OutputStreamWriter(new FileOutputStream("ValidationResults.txt")));
    System.out.println("Writing in TEXT file: " + "type=" + key + ";value=" +  value + ";" +  valResult);
    writer.newLine();
    writer.write("\ntype=" + key + ";value=" +  value + ";" + valResult + "\n");
    writer.flush();
    writer.close();
}
blackpanther
  • 10,998
  • 11
  • 48
  • 78
Mlad3n
  • 133
  • 1
  • 4
  • 14
  • It will be a good idea to add the language and platform tags to this question. – Abizern Jul 04 '13 at 10:31
  • 1
    You need to open the file in Append(Upate) mode. – Subir Kumar Sao Jul 04 '13 at 10:31
  • What language do you use? What is the target OS or device? Put this information in question tags to attract more experts. – Artemix Jul 04 '13 at 10:31
  • possible duplicate of [How to write data with FileOutputStream without losing old data?](http://stackoverflow.com/questions/8544771/how-to-write-data-with-fileoutputstream-without-losing-old-data) – Mat Jul 04 '13 at 10:32
  • Im sorry, Abizem... i work in java, eclipse... – Mlad3n Jul 04 '13 at 10:33
  • You have almost the same code in the two blocks. You can factor this out. The only difference is the value for `valResult`. In addition, whenever you see or think of writing `(x == true)` remember that this will be the same as `x` for any boolean expression `x`. Thus, if `x` is a boolean expression, then the following will all be the same: `x==true`, `(x==true)==true`, `((x==true)==true)==true`. Is it true that it is the case that the truth is that you don't understand this? – Ingo Jul 04 '13 at 10:38

1 Answers1

2

User a FileWriter. Thats should solve ur problem. The True parameter says that the next line will append to the existing file. if u use false instead the file would be overridden.

new BufferedWriter(new FileWriter("file.txt", true));
Dennis Kriechel
  • 3,719
  • 14
  • 40
  • 62