32

I have a string that contains new lines. I send this string to a function to write the String to a text file as:

    public static void writeResult(String writeFileName, String text)
    {
        try
        {
        FileWriter fileWriter = new FileWriter(writeFileName);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        bufferedWriter.write(text);

        // Always close files.
        bufferedWriter.close();

        }
        catch(IOException ex) {
            System.out.println("Error writing to file '"+ writeFileName + "'");}
    } //end writeResult function

But when I open the file, I find it without any new lines. When I display the text in the console screen, it is displayed with new lines. How can I write the new line character in the text file.

EDIT: Assume this is the argument text that I sent to the function above:

I returned from the city about three o'clock on that
may afternoon pretty well disgusted with life.
I had been three months in the old country, and was

How to write this string as it is (with new lines) in the text file. My function write the string in one line. Can you provide me with a way to write the text to the file including new lines ?

EDIT 2: The text is originally in a .txt file. I read the text using:

while((line = bufferedReader.readLine()) != null)
{
sb.append(line); //append the lines to the string
sb.append('\n'); //append new line
} //end while

where sb is a StringBuffer

user2192774
  • 3,807
  • 17
  • 47
  • 62
  • 8
    If you are using a windows machine, try "\r\n" as new lines instead of just "\n" – shiraz Sep 29 '13 at 23:15
  • See **all** the answers here: http://stackoverflow.com/questions/207947/java-how-do-i-get-a-platform-independent-new-line-character – PM 77-1 Sep 29 '13 at 23:16
  • If the string contains newlines so will the output file. Ergo either your string doesn't contain newlines, or the file does. As you say it displays with newlines, it contains newlines. So what's your question? – user207421 Sep 30 '13 at 01:34
  • It' s worked for me. I just put in new FileWriter(arquivo, true) the boolean attribute to not erase my file content. – linhadiretalipe Feb 11 '16 at 18:23

9 Answers9

38

In EDIT 2:

while((line = bufferedReader.readLine()) != null)
{
  sb.append(line); //append the lines to the string
  sb.append('\n'); //append new line
} //end while

you are reading the text file, and appending a newline to it. Don't append newline, which will not show a newline in some simple-minded Windows editors like Notepad. Instead append the OS-specific line separator string using:

sb.append(System.lineSeparator()); (for Java 1.7 and 1.8) or sb.append(System.getProperty("line.separator")); (Java 1.6 and below)

Alternatively, later you can use String.replaceAll() to replace "\n" in the string built in the StringBuffer with the OS-specific newline character:

String updatedText = text.replaceAll("\n", System.lineSeparator())

but it would be more efficient to append it while you are building the string, than append '\n' and replace it later.

Finally, as a developer, if you are using notepad for viewing or editing files, you should drop it, as there are far more capable tools like Notepad++, or your favorite Java IDE.

lreeder
  • 12,047
  • 2
  • 56
  • 65
  • I edited my so I added your suggested line before: bufferedWriter.write(text); but nothing has changed. Still I can not write new lines to the file. The text appears in a single line inside the file. – user2192774 Sep 29 '13 at 23:35
  • 1
    `String.replaceAll()` doesn't update the String it's called on, since Java Strings are immutable. Are you using the value returned by `replaceAll`? See my updated answer. – lreeder Sep 30 '13 at 01:57
21

SIMPLE SOLUTION

File file = new File("F:/ABC.TXT");
FileWriter fileWriter = new FileWriter(file,true);
filewriter.write("\r\n");
Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
user3205467
  • 217
  • 2
  • 6
19

The BufferedWriter class offers a newLine() method. Using this will ensure platform independence.

JustDanyul
  • 13,813
  • 7
  • 53
  • 71
7

bufferedWriter.write(text + "\n"); This method can work, but the new line character can be different between platforms, so alternatively, you can use this method:

bufferedWriter.write(text);
bufferedWriter.newline();
nhgrif
  • 61,578
  • 25
  • 134
  • 173
  • This will not work in my case. I send the String to the function. How can I know if there is a '\n' in the String I sent? The '\n' is more than once. For example, my String is 4 or 5 lines. How to write these lines to the file? – user2192774 Sep 29 '13 at 23:16
  • If the `String` that the `text` variable holds is multiline, then the `\n` characters need to be imbedded within the `String` itself. – nhgrif Sep 29 '13 at 23:17
  • And now that I reread your original post, for clarification, what prints to the console is automatically word-wrapped. If you change the size of the console, the new lines will start at different spots. When saving to a .txt, you won't get automatic word wrapping. – nhgrif Sep 29 '13 at 23:19
  • Agree. But could you see my posted code. How to do this? I can think of a loop to check if the text contains a '\n' but this is not practical for long Strings. That's why I need help. – user2192774 Sep 29 '13 at 23:20
  • When you print to the console, the text will automatically wordwrap and create newlines. It does this without the newline character. If your string already has newline characters in it but they're not printing to the text file, then try a method similar to what @lreeder suggested: `text.replaceAll("\n", System.lineSeparator())` – nhgrif Sep 29 '13 at 23:33
  • Could you please try it. It does not change anything to me. Same problem. The file is single line even after I added: text.replaceAll("\n", System.lineSeparator()). – user2192774 Sep 29 '13 at 23:39
  • Then it would be because you don't have any newline characters in your string. Do you understand what I mean by wordwrap? Run your program printing to the console. Now resize your console. Resize it to all different sizes. The string appears on a varying number of lines because the CONSOLE wordwraps the string. There are no newline characters in the string. And if there are no newline characters in the string and no way of making newlines within the string, then it will never print to multiple lines when sending it to a file. – nhgrif Sep 29 '13 at 23:41
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/38302/discussion-between-nhgrif-and-user2192774) – nhgrif Sep 29 '13 at 23:41
3

Split the string in to string array and write using above method (I assume your text contains \n to get new line)

String[] test = test.split("\n");

and the inside a loop

bufferedWriter.write(test[i]);
bufferedWriter.newline();
User123456
  • 2,492
  • 3
  • 30
  • 44
3

This approach always works for me:

String newLine = System.getProperty("line.separator");
String textInNewLine = "this is my first line " + newLine + "this is my second 
line ";
Rahul k
  • 69
  • 3
1

Put this code wherever you want to insert a new line:

bufferedWriter.newLine();
1
    PrintWriter out = null; // for writting in file    
    String newLine = System.getProperty("line.separator"); // taking new line 
    out.print("1st Line"+newLine); // print with new line
    out.print("2n Line"+newLine);  // print with new line
    out.close();
Tarit Ray
  • 944
  • 12
  • 24
0

Here is a snippet that gets the default newline character for the current platform. Use System.getProperty("os.name") and System.getProperty("os.version"). Example:

public static String getSystemNewline(){
    String eol = null;
    String os = System.getProperty("os.name").toLowerCase();
    if(os.contains("mac"){
        int v = Integer.parseInt(System.getProperty("os.version"));
        eol = (v <= 9 ? "\r" : "\n");
    }
    if(os.contains("nix"))
        eol = "\n";
    if(os.contains("win"))
        eol = "\r\n";

    return eol;
}

Where eol is the newline

Lux
  • 1,540
  • 1
  • 22
  • 28