Reputation: 71
I have one JTextArea and a Submit button in Java Swing. Need 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.
try {
BufferedWriter fileOut = new BufferedWriter(new FileWriter("filename.txt"));
String myString1 =jTextArea1.getText();
String myString2 = myString1.replace("\r", "\n");
System.out.println(myString2);
fileOut.write(myString2);
fileOut.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Please get me some suggestions
Upvotes: 4
Views: 11327
Reputation: 19
This is what i thought up of :
public void actionPerformed(ActionEvent event) {
BufferedWriter writer;
try {
writer = new BufferedWriter(new FileWriter("SimpleText.txt",
false));
text.write(writer);
writer.close();
JOptionPane.showMessageDialog(null, "File has been saved","File Saved",JOptionPane.INFORMATION_MESSAGE);
// true for rewrite, false for override
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error Occured");
e.printStackTrace();
}
}
Hope this helps
Upvotes: 0
Reputation:
Why did you replace \r
by \n
?
The line separator should be "\r\n"
.
Upvotes: 0
Reputation: 44808
Why not use JTextArea
's built in write
function?
JTextArea area = ...
try (BufferedWriter fileOut = new BufferedWriter(new FileWriter(yourFile))) {
area.write(fileOut);
}
Upvotes: 18
Reputation: 13063
Replace all \r and \n with:
System.getProperty("line.separator")
This will make your code platform-independent and will write new lines to the files where necessary.
Edit: since you use BufferedWriter, you could also use the newLine() method
Upvotes: 2