DamDev DamDev - 1 year ago 56
Java Question

Saving content from JTextArea into file with line separators

I have a problem with writing to file.

Generally I am creating simple text editor. I load file in this way:

try(BufferedReader br = new BufferedReader(new FileReader(currentlyEditedFile))) {
String line = "";
while((line = br.readLine()) != null) {
editor.append(line + "\n");
} catch(Exception ex) {

and the after some modifications, I want to save(write) it back to the file.

I am doing it in this way:

try(PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(currentlyEditedFile)))) {
String[] lines = editor.getText().split("\\n");//Tried \n, \\n
for(String s : lines)
} catch(Exception ex) {

and the content goes to the file, but it is all in one line. Any ideas how to write line by line?


If you are using Windows, then you should do:

editor.append(line + "\r\n");

Because the new-line in Windows is denoted by \r\n, i.e., a carriage-return and a line-feed.