Silvan Theuma
Silvan Theuma

Reputation: 311

how to save a text file in java

I am doing a text editor program, but I am having trouble when saving the content from the text area to a .txt file. The content written does not show up. Instead a bunch of coding shows up.

Can anyone help me with this.

JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("C:\\Users\\Silvan\\Desktop"));
int retrival = chooser.showSaveDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) 
{
    try(FileWriter fw = new FileWriter(chooser.getSelectedFile()+".txt"))
    {
        fw.write(txt1.toString());
    }   
    catch (Exception ex) 
    {
         ex.printStackTrace();
    }
}
}                                          

Upvotes: 2

Views: 4497

Answers (3)

camickr
camickr

Reputation: 324197

Just use the JTextArea write() method:

FileWriter writer = new FileWriter( ... );
BufferedWriter bw = new BufferedWriter( writer );
textArea.write( bw );

Upvotes: 0

unfamous
unfamous

Reputation: 611

It's happening because you're not getting the text of the JTextArea but in stead your saving the JTextArea it self

use :

fw.write(txt1.getText());

Upvotes: 2

Jason Sperske
Jason Sperske

Reputation: 30446

Odd that comment was removed but from the documentation getText() is what you are looking for:

Returns the text contained in this TextComponent.

Upvotes: 0

Related Questions