Writing multiline JTextArea content into file

2019-01-12 08:31发布

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条回答
Deceive 欺骗
2楼-- · 2019-01-12 09:08

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);
查看更多
登录 后发表回答