0

Im trying to write a text to file, but it overwrites whats inside, can somebody explain how to check if the text exists and then put a new line and write? Here is the code I am working with:

try
{
    if (!file.exists())
    {
        file.createNewFile();
    }

    FileWriter fw =
        new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.newLine();
    bw.write(petName);
    bw.close();
    System.out.println("Done!");
}
catch (IOException exc)
{
    System.out.println(exc);
}

Thank you for any kind of help.

Sean Mickey
  • 7,618
  • 2
  • 32
  • 58
MariusJ
  • 83
  • 8

2 Answers2

0

how to check if the text exists and then put a new line and write?

Use File#length() to check if the text exists in the file.

if(file.length()>0){
    bw.newLine();
}

Note: Open the file in append mode if you don't want to override the existing content of the file.

Braj
  • 46,415
  • 5
  • 60
  • 76
-1

Use following to append if file exists.

FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
Timuçin
  • 4,653
  • 3
  • 25
  • 34