Hafsah H
Hafsah H

Reputation: 141

How do I write multiple lines to a text file in 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.

Upvotes: 4

Views: 22081

Answers (3)

J-Alex
J-Alex

Reputation: 7127

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.

Upvotes: 6

Roushan
Roushan

Reputation: 4440

just add \n or \r\n platform new line character based on system at the end of string in write method

try{
    for(int i = 1; i < 6; i++){
           info.write("Hello\n");
           info.write("Bonjour\n");
           ...

           }
    }
    catch (Exception e) {
    System.out.println("A write error has occurred");
}
finally{
    info.close();
}

Upvotes: 0

achAmh&#225;in
achAmh&#225;in

Reputation: 4266

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");
}

Upvotes: 2

Related Questions