I am trying to write a String(lengthy but wrapped), which is from JTextArea. When the string printed to console, formatting is same as it was in Text Area, but when I write them to file using BufferedWriter, it is writing that String in single line.
Following snippet can reproduce it:
public class BufferedWriterTest {
public static void main(String[] args) throws IOException {
String string = "This is lengthy string that contains many words. So\nI am wrapping it.";
System.out.println(string);
File file = new File("C:/Users/User/Desktop/text.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(string);
bufferedWriter.close();
}
}
What went wrong? How to resolve this? Thanks for any help!
Text from a
JTextAreawill have\ncharacters for newlines, regardless of the platform it is running on. You will want to replace those characters with the platform-specific newline as you write it to the file (for Windows, this is\r\n, as others have mentioned).I think the best way to do that is to wrap the text into a
BufferedReader, which can be used to iterate over the lines, and then use aPrintWriterto write each line out to a file using the platform-specific newline. There is a shorter solution involvingstring.replace(...)(see comment by Unbeli), but it is slower and requires more memory.Here is my solution – now made even simpler thanks to new features in Java 8: