Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write multiple lines to a text file in Java?

Tags:

java

So I want to create and write to a file in Java. I know how to do it with one line, but I'm wondering how I write multiple lines to a single file.

import java.io.FileWriter;
import java.io.BufferedWriter;

public class WritingToAFile {

public static void main(String[] args) {

   try{ 
   FileWriter fstream = new FileWriter ("P:/Computer Science/greeting.txt");
   BufferedWriter info = new BufferedWriter(fstream);

   for(int i = 1; i < 6; i++){
       info.write("Hello");
       info.newLine();
       info.write("Bonjour");
       info.newLine();
       info.write("Guten tag");
       info.newLine();
       info.write("Aloha");
       info.newLine();
       info.write("Nihao");
       info.close();
       }catch(Exception e){
          System.out.println("A write error has occurred");
    }   
  }
}

I know it's wrong right now, but I'm not sure what I did wrong. Help would be much appreciated! I'm only a beginner so I'm really lost.

like image 387
Hafsah H Avatar asked Sep 07 '25 04:09

Hafsah H


2 Answers

You're closing you're file each iteration - info.close(); - that's the reason you'll have the exception. You need to close the file once you'll finish to write to it.

There is nothing wrong with newLine(); approach. However you can make it shorter using new line character.

"\n" - is a new line separator for Unix-based systems.

"\r\n" - is a new line separator for Windows systems.

"%n" is a platform independent new line separator.

for(int i = 1; i < 6; i++) {
    info.write(String.format("Hello%n"));
}
info.close();

The second issue is here that you're not closing FileWriter itself.

If you're using Java 7+, I would recommend to do it using try-with-resources to to get rid of finally blocks:

public class Main {

    public static void main(String[] args) {
        try (FileWriter fstream = new FileWriter("greeting.txt");
             BufferedWriter info = new BufferedWriter(fstream)) {
            for (int i = 1; i < 6; i++) {
                info.write(String.format("Hello%n"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

File output:

Hello
Hello
Hello
Hello
Hello

UPDATE:

All the input-output operations require to deal with streams, channels, file descriptors (like FileWriter, BufferedWriter in your particular case). These streams should be closed carefully to release system resources. Failing to do so may lead to resources leak. Despite you closed info you forgot to close fstream in the code.

When you use the try-with-resources statement correctly, then you will never have to close streams explicitly. The try-with-resources statement ensures that each resource is closed at the end of the statement.

like image 95
J-Alex Avatar answered Sep 09 '25 02:09

J-Alex


You have almost got it right, in fact, it's nothing to do with info.newLine(); but rather the syntax of your code.

Your catch is actually after your for loop, and not connected to the try.

And you also close the stream in the for loop, instead of after it has completed (this would cause an IOException).

Sample:

try {
    FileWriter fstream = new FileWriter("P:/Computer Science/greeting.txt");
    BufferedWriter info = new BufferedWriter(fstream);
    for (int i = 1; i < 6; i++) {
        info.write("Hello");
        info.newLine();
        info.write("Bonjour");
        info.newLine();
        info.write("Guten tag");
        info.newLine();
        info.write("Aloha");
        info.newLine();
        info.write("Nihao");
    }
    info.close();
} catch (Exception e) {
    System.out.println("A write error has occurred");
}
like image 23
achAmháin Avatar answered Sep 09 '25 01:09

achAmháin