Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java FileWriter how to write to next Line

Tags:

java

file

newline

I used the code below to write record into a File. The record can be written in the file, but is append in one Line, each time I call this method example:

Hello WorldHello WorldHello WorldHello World

How can I modify the code so the output look like below, so that when read the text I can use line.hasNextLine() to check?

Hello World
Hello World
Hello World
Hello World

        // Create file
        FileWriter fstream = new FileWriter(fileName, true);
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(c.toString());
        //Close the output stream
        out.close();

        // Code I used to read record I am using | as a seperator name and id
        String fileName = folderPath + "listCatalogue.txt";
        String line = "";
        Scanner scanner;
        String name, id;
        scanner = new Scanner(fileName);
        System.out.println(scanner.hasNextLine());
        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            System.out.println(line);
            StringTokenizer st = new StringTokenizer(line, "|");
            name = st.nextToken();
            id = st.nextToken();
            catalogues.add(new Catalogue(name, id));
        }
like image 789
user236501 Avatar asked Nov 04 '11 05:11

user236501


People also ask

How do you write to a new line in FileWriter?

write("\r\n"); or better writer. write(System.

How do you write to the next line in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

How do you write multiple lines in a text file in Java?

boolean append = true; String filename = "/path/to/file"; BufferedWriter writer = new BufferedWriter(new FileWriter(filename, append)); // OR: BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename, append))); writer. write(line1); writer. newLine(); writer.

How do I add a new line in FileOutputStream?

write("\n".


2 Answers

I'm not sure if I understood correctly, but is this what you mean?

out.write("this is line 1");
out.newLine();
out.write("this is line 2");
out.newLine();
...
like image 127
aleph_null Avatar answered Sep 21 '22 14:09

aleph_null


out.write(c.toString());
out.newLine();

here is a simple solution, I hope it works

EDIT: I was using "\n" which was obviously not recommended approach, modified answer.

like image 37
Zohaib Avatar answered Sep 25 '22 14:09

Zohaib