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 = "";
editor.setText("");
while((line = br.readLine()) != null) {
editor.append(line + "\n");
}
} catch(Exception ex) {
ex.printStackTrace();
}
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)
pw.println(s);
} catch(Exception ex) {
ex.printStackTrace();
}
and the content goes to the file, but it is all in one line. Any ideas how to write line by line?
You may load content of a text file into JTextArea
in following simple way:
JTextArea textArea = new JTextArea();
FileReader reader = new FileReader("D:/text1.txt");
textArea.read(reader, "Content of File");
reader.close();
You may write content of JTextArea
to a file in following simple and platform independent way:
PrintWriter pw=new PrintWriter("D:/text1.txt");
textArea.write(pw);
pw.close();
Hope, this is helpful to you.
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
, ie, a carriage-return and a line-feed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.