Writing multiline JTextArea content into file

2019-01-12 08:50发布

问题:

I have to write the content of textarea into a file with line breaks. I got the output like, it is written as one string in the file.

public void actionPerformed(ActionEvent ev) {

text.setVisible(true);
String str= text.getText();
System.out.println(str);

try {
    BufferedWriter fileOut = new BufferedWriter(new FileWriter("filename.txt")); 


    fileOut.write(str);

    fileOut.close();
} catch (IOException ioe) {
    ioe.printStackTrace();
}
}

Example

Output should be:

I
am
King.

but it is showing:

IamKing.

Please get me some suggestions

回答1:

Use JTextComponent.write(Writer):

Stores the contents of the model into the given stream. By default this will store the model as plain text.

E.G.

BufferedWriter writer = new BufferedWriter(new FileWriter("filename.txt"));
text.write(writer);