Reputation: 245
hello guys i have a code in my application that save the data on the jtextarea to .txt file. The problem is when i type multiple line text on my jtextarea and save it to ".txt" file, the the whole data written as one line text.
String content = txtDescriptionCity.getText(); //jtextarea
File file = new File("C:\\Tour v0.1\\Descriptions\\City\\"+txtcityname.getText()+".txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
i want to write the text as it is on the jtextarea... Like this
"Text line one
Text line two
Text line three"
Upvotes: 0
Views: 121
Reputation: 324088
Don't reinvent the wheel. Just use:
textArea.write(...);
It will replace new line characters in the Document with the proper new line string for the platform you are using.
Upvotes: 2
Reputation: 2023
First we read out the systems line seperator, then we split the content String and write each part of the new String Array to the file. The new FileWriter(*,true);
garanties that the content is appended.
String seperator = System.lineSeparator();
String[] lines = content.split("\n");
FileWriter writer = new FileWriter(file ,true);
for (int i = 0 ; i < lines.length; i++){
writer.append(lines[i]+seperator);
}
writer.close();
}
Upvotes: 0
Reputation: 109547
If the lines where entered by Enter, do:
content = content.replaceAll("\r?\n", "\r\n");
This then uses the real line break under Windows: \r\n
(CR+LF). A single \n
is not shown in Notepad. Unlikely though.
If the multiple lines were caused by word wrapping, the case is more difficult.
If by adding spaces,
content = content.replaceAll(" +", "\r\n");
Upvotes: 1
Reputation: 1531
You can split and then write, in my code i am splitting the string based on "."(fullstops).
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (String retval: content.split(".")){
bw.write(retval+".");
bw.newLine();
}
Upvotes: 0