How can I make a BufferedWriter write on the bottommost defined line in a text file?

public static void print(String id) {
    try{
        FileWriter fstream = new FileWriter("out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(id +"\n");
        out.close();
    }catch (Exception e){
    }
}   

I call this method hundreds of thousands of times during run-time, but it keeps overwriting the first line. How can I make it start on the bottommost line? (I take care of the next line being defined with the escape sequence.)

Or is there a more elegant solution? Opening and closing a text file hundreds of thousands of times to store my simulation results is not very efficient. But then again, if I have out.close in main at the end of all execution, I clash with a lot of people who say that everything to do with I/O should go in a try/catch block (also, I'd have to handle the function never being executed and out not being defined etc.).

Upvotes: 0

Views: 105

Answers (2)

SamIAm
SamIAm

Reputation: 2491

I am not sure what you are looking for but if you're looking for a way to append to the file, you can try

FileWriter fstream = new FileWriter("out.txt", true);

as the constructor

public FileWriter(File file, boolean append)

will append to the file given and not overwrite it.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500555

Yes, you could just change your code to use new FileWriter("out.txt", true). That would append to the file. However, there are other alternatives:

  • I'd strongly recommend using OutputStreamWriter (wrapped around a FileOutputStream) instead of FileWriter. That way you can specify the encoding for your file. What encoding do you want it to be? (You can still append this way - you just use an appropriate FileOutputStream constructor.)

  • Why are you using a BufferedWriter? You're writing a string to the writer, then closing the writer. What effect do you expect buffering to have?

  • Currently you're swallowing all exceptions. Even if you do want to silently swallow IOException, you shouldn't be swallowing other exceptions. Always catch specific exceptions where you can.

  • You're not the file if an exception is thrown. You should always close resources with a finally block, or use the try-with-resources statement in Java 7.

  • Do you really need to reopen the file every time you write? Why not leave it open, and just write to it whenever you need to? Then close it just on application shutdown.

Upvotes: 1

Related Questions