3

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.

Hafsah H
  • 131
  • 1
  • 1
  • 3

3 Answers3

5

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.

J-Alex
  • 6,881
  • 10
  • 46
  • 64
  • Ah, I had no idea there were other line separators, newLine(); was the only one we ever learnt in class, that's really useful, thanks! Sorry but could you explain the second bit please? I don't really get it. – Hafsah H May 11 '18 at 13:45
  • @Hafsah H Please look at the updated part of the answer. Do not forget to accept the answer which was most useful and solved your problem. – J-Alex May 11 '18 at 14:12
2

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");
}
achAmháin
  • 4,176
  • 4
  • 17
  • 40
0

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();
}
Roushan
  • 4,074
  • 3
  • 21
  • 38
  • Are you sure the BufferedWriter will convert it to \r or \r\n on the respective systems? – JayC667 May 09 '18 at 16:10
  • look the code and path of file, for sys platform before pointing – Roushan May 09 '18 at 16:12
  • Well, yes. Looks like Windows to me (even though you should use backslashes instead of slashes)... So, as we all know, Windows uses \r\n line breaks, any other might lead to problems. And that's why I mentioned it. And both BufferedWriter and FileWriter call Writer (http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/Writer.java#Writer.write%28java.lang.String%29) or use java.lang.String's getChars method that will not adapt the proper line separator. So read and understand before you cry about someone 'pointing'. – JayC667 May 09 '18 at 16:23
  • its not looks like , its windows, cry -> haha why should i do, "\n" works for new line on windows, and why was that link attached i didnt found any thing relative that u mentioning – Roushan May 09 '18 at 18:22
  • Well, at least you've modified a bit of your code. Even though it's not really correct yet, it's already a step in the right direction... Check `System.getProperty("line.separator")` or `System.lineSeparator()` for a completely correct answer, or the thread https://stackoverflow.com/questions/36796136/difference-between-system-getpropertyline-separator-and-n for an in-depth understanding. Thanx you, for making this platform great again^^ – JayC667 May 10 '18 at 01:34