ratnesh singh
ratnesh singh

Reputation: 5

jTextArea saves only first line of text in text file using BufferedReader?

I am trying to save the multiple line output in a text file from my jTextArea(named as "outputarea" in a code) to my desired path, Everything is OK but the file being saved do not contain the whole output, but only first line oof text. I am using "\n" to break the line in jtextarea while giving multiple line output, does that make any difference or any other problem in this code, This code is just the code on saveAs button, output is coming from another methods I've created. Thanks in Advance!

private void saveAs() {

 FileDialog fd = new FileDialog(home.this, "Save", FileDialog.SAVE);
 fd.show();
 if(fd.getFile()!=null)
 {
 fn=fd.getFile();
 dir=fd.getDirectory();
 filename = dir + fn +".txt";
 setTitle(filename);
 try
 {

 DataOutputStream d=new DataOutputStream(new FileOutputStream(filename));
 holdText = outputarea.getText();
 BufferedReader br = new BufferedReader(new StringReader(holdText));
 while((holdText = br.readLine())!=null)
 {
 d.writeBytes(holdText+"\r\n");
 d.close();
 }
 }
     catch (Exception e)
     {
     System.out.println("File not found");
     }
outputarea.requestFocus();
save(filename);
 }

}

Upvotes: 0

Views: 109

Answers (1)

STaefi
STaefi

Reputation: 4377

You should put the d.close(); after the completion of while loop, because just after writing the first line in the file using DataOutputStream, you are closing it and you don't let it to fulfill the whole job.

You can see even an error is wrote in your console:

File not found

This is not because it doesn't find your file, it's because in the iterations after the first, it tries to write into a closed stream. So only the first line is wrote then. So change you code like this:

while ((holdText = br.readLine()) != null) {
    d.writeBytes(holdText + "\r\n");
}
d.close();

Also I can advise to use a PrintWriter instead of DataOutputStream. Then you can easily change the writeBytes into println method. In this way you don't need to append \r\n manually to each line you write.

Another good hint is to use a try-with-resource (in case you use java 7 or later) or at least a finally block to close your streams either way:

String holdText = outputarea.getText();
try (PrintWriter w = new PrintWriter(new File(filename));
     BufferedReader br = new BufferedReader(new StringReader(holdText))) {
    while ((holdText = br.readLine()) != null) {
        w.println(holdText);
    }

} catch (Exception e) {
        System.out.println("File not found");
}

Good Luck.

Upvotes: 3

Related Questions