19

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!

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Ahamed
  • 39,245
  • 13
  • 40
  • 68

5 Answers5

18

Text from a JTextArea will have \n characters 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 a PrintWriter to write each line out to a file using the platform-specific newline. There is a shorter solution involving string.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:

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");

    writeToFile(string, file);
}

private static void writeToFile(String string, File file) throws IOException {
    try (
        BufferedReader reader = new BufferedReader(new StringReader(string));
        PrintWriter writer = new PrintWriter(new FileWriter(file));
    ) {
        reader.lines().forEach(line -> writer.println(line));
    }
}
Kevin K
  • 9,344
  • 3
  • 37
  • 62
  • 2
    uhm, stacking all these readers to do simple replacement? `string.replace("\\n", System.getProperty("line.separator"));` – unbeli Feb 08 '12 at 19:06
  • @unbeli, Replacement is quick if the String is short, for very lengthier strings, the above approach holds good. I have tested it though. – Ahamed Feb 08 '12 at 20:30
  • 1
    @unbeli - `String.replace()` requires creating a new object, which temporarily doubles the memory requirement, so it's not ideal for large amounts of data. Though granted, with the data coming from a `JTextArea`, I can't imagine the string would be terribly large, so it would probably work just as well for the most part – Kevin K Feb 08 '12 at 20:46
7

Please see the following question on how to appropriately handle newlines.

How do I get a platform-dependent new line character?

Basically you want to use

String newLineChar = System.getProperty("line.separator");

and then use the newLineChar instead of "\n"

Community
  • 1
  • 1
jluzwick
  • 2,005
  • 1
  • 15
  • 23
3

I just ran your program, and adding a carriage return (\r) before your newline (\n) did the trick for me.

If you want to get a system independent line separator, one can be found in the system propery line.separator

String separator = System.getProperty("line.separator");
String string = "This is lengthy string that contains many words. So" + separator
            + "I am wrapping it.";
nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
1

If you wish to keep the carriage return characters from a Java string into a file. Just replace each break line character (which is recognized in java as: \n) as per the following statement:

TempHtml = TempHtml.replaceAll("\n", "\r\n");

Here is an code example,

        // When Execute button is pressed
        String TempHtml = textArea.getText();
        TempHtml = TempHtml.replaceAll("\n", "\r\n");
        try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/temp.html"))) {
            out.print(TempHtml);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(TempHtml);
Supercoder
  • 1,066
  • 1
  • 10
  • 16
0

If you are using a BufferedWriter, you could also use the .newline() method to re-add the newline based on your platform.

See this related question: Strings written to file do not preserve line breaks

Community
  • 1
  • 1
Christian Vielma
  • 15,263
  • 12
  • 53
  • 60