Java FileWriter only writing first line

By : Nick
Source: Stackoverflow.com
Question!

I am working on a Java application that has a JTextArea for users to input text. It can be any amount of lines, however I am running into a problem with my FileWriter, where it's only saving the first line of any input. I've never used Swing or FileWriter before at all, so I may be getting this quite wrong, but here's my code:

FileWriter fw = null;
    try {
        fw = new FileWriter(lastSavedFile);
        details.write(fw);
    } catch (IOException exception) {
        System.err.println("Error saving file");
        exception.printStackTrace();
    } finally {
        if (fw != null) {
            try {
                fw.close();
            } catch (IOException exception) {
                System.err.println("Error closing writer");
                exception.printStackTrace();
            }
        }
    }

Thanks!

By : Nick


Answers

Use the constructor like this: FileWriter writer = new FileWriter("lastsavedfilee.txt",true);



Try flushing the FileWriter before closing it in the finally block. .

.
if (fw != null) 
{
   try 
   {
       fw.flush();
       fw.close();
   } catch (IOException exception) 
   {
       System.err.println("Error closing writer");
       exception.printStackTrace();
   }
}
.
.

I agree with @Yishai ... And if possible then give the use of details function. This would help others to answer it.

By : Favonius


This video can help you solving your question :)
By: admin