Ricco
Ricco

Reputation: 775

java writing to a text file

I would like the following to be printed

test1

test2

test3

test4

But I can't seem to get the text to the next line.

Please help

import java.io.*;

public class MainFrame {
    public static void main(String[] args) {
        try {
        BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
            for (int i = 0; i < 4; i++) {
                out.write("test " + "\n");
            }
            out.close();
        } catch (IOException e) {}
    }
}

Upvotes: 9

Views: 95404

Answers (6)

Abbas
Abbas

Reputation: 3258

The given answer - System.getProperty("line.separator")is good enough, but also try out.write("test " + "\r\n"); it might work, as line break in some OS is \r\n and not \n

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You need have two \n\n to have a blank line. Try

out.write("test " + "\n\n");

In your case(with one \n), it will break the current line and move to a new line(which is the next line) but the blank line will not come.

The newline character can be depended on the platform, so it is better to get the new line character from the java system properties using

public static String newline = System.getProperty("line.separator");

Upvotes: 8

Babak Naffas
Babak Naffas

Reputation: 12561

Considering you have an empty catch block, it could be that you're getting an exception and hiding it. Remove the catch block and add throw IOException to your method definition so if you're getting an exception you can see it.

Upvotes: 0

Ryan
Ryan

Reputation: 3215

Try out.newLine();

So, it would be

for (int i = 0; i < 4; i++) {
    out.write("test " + "\n");
    out.newLine();
}

Source (Java API)

Upvotes: 35

MeBigFatGuy
MeBigFatGuy

Reputation: 28568

If you want to generate text, it's probably easier to create a PrintWriter on top of that BufferedWriter, and use the methods in PrintWriter (like println) to do the writing.

Upvotes: 3

Sam Becker
Sam Becker

Reputation: 19636

Depending on what text editor you are opening the file with and what operating system you are using you might have to use "\r\n" instead of just "\n".

Give it a try.

Upvotes: 0

Related Questions