Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java writing to a text file

Tags:

java

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) {}
    }
}
like image 704
Ricco Avatar asked May 03 '11 05:05

Ricco


2 Answers

Try out.newLine();

So, it would be

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

Source (Java API)

like image 52
Ryan Avatar answered Oct 12 '22 04:10

Ryan


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");
like image 44
Arun P Johny Avatar answered Oct 12 '22 04:10

Arun P Johny