Skip to content
Advertisement

How can I open a file in java without its contents been removed?

I want my program to create a file for the user (just for the first time) and write some information to it (it’s not just a line and also can be adjusted anytime later). So I did this:

public void write() {
    try {
        file = new File("c:\Users\Me\Desktop\text.txt");
        
        if(!file.exists())            // I found this somewhere on the internet for File class
            file.createNewFile();     // not to remove contents. I have no idea if it works
        
        writer = new Formatter(file);
    
    } catch(Exception e) {
        e.printStackTrace();
    }

    writer.format("%s  %s ", nameInput.getText(),lastNameInput.getText());
    
    writer.close();
}

It works but there some problems:

  1. When the file gets opened later, as default, the File class removes its contents.

  2. When the information is written to the file and Formatter got closed, next time somewhere else in the program when I use it again to write to the file, the information gets updated and not added to the previous ones. And if I don’t close it, it won’t write.

Advertisement

Answer

As people mentioned above, I had to pass the file through the constructor of FileWriter class. this way my first problem got solved (I mentioned them in the question) and for the second one, I had to reopen the Formatter whenever I wanted to add more.

public void write() {

  try { 
    
    writer = new Formatter(new FileWriter(file,true);

} catch(Exception e) {
    e.printStackTrace();
}

writer.format("%s  %s ", nameInput.getText(),lastNameInput.getText());

writer.close();  }

creation and initialization of file should be done once and outside the method.

Advertisement