1

I want to write some data to a file and here is my code:

for (Season s : seasons) {
            if (s.getYear() >= start && s.getYear() <= end) {
                line += s.getYear() + ", " + s.getWinTeamName() + ", "
                        + s.getMinorPremiersTeam() + ", "
                        + s.getWoodenSpoonTeam()+ "\n"; }
}
System.out.println("File created.\n"); // Informing the user about
// the creation of the file.
out.write(line);
out.close();

My file is created but this is what I get:

2005, Wests Tigers, Parramatta, Newcastle2006, Broncos, Storm, Rabbitohs

But I want it to be:

2005, Wests Tigers, Parramatta, Newcastle
2006, Broncos, Storm, Rabbitohs

I thought the adding the "\n" at the end of the line variable would fix that but it hasn't.

Any suggestions on how to fix that?

Eran
  • 387,369
  • 54
  • 702
  • 768
roro
  • 713
  • 2
  • 6
  • 19
  • It seems OK. Try replacing the \n with \r\n, some text editors (Notepad, for example) don't show \n correctly. – manabreak May 31 '13 at 10:01
  • Your println() doesn't need a `\n`. The methodname stands for `print line` so it already uses new lines. – Menno May 31 '13 at 10:04
  • For more generic code, you may want to use [a line separator function](http://stackoverflow.com/questions/207947/java-how-do-i-get-a-platform-independent-new-line-character) instead. – Bernhard Barker May 31 '13 at 10:04

3 Answers3

3

You need to use the system-specific newline separator. See System.lineSeparator

BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56
1

If you use the java.io.BufferedWriter, the .newLine() method will insert the appropriate line separator.

for (Season s : seasons) 
{
   if (s.getYear() >= start && s.getYear() <= end)
   {
      String line = s.getYear() + ", " + s.getWinTeamName() + ", "
                        + s.getMinorPremiersTeam() + ", "
                        + s.getWoodenSpoonTeam();
      out.write(line);
      out.newLine();
   }
}
Simon Curd
  • 790
  • 5
  • 12
0
for (Season s : seasons) {
        if (s.getYear() >= start && s.getYear() <= end) {
            line += s.getYear() + ", " + s.getWinTeamName() + ", "
                    + s.getMinorPremiersTeam() + ", "
                    + s.getWoodenSpoonTeam()+ "\r\n"; }
}

System.out.println("File created.\n"); // Informing the user about
                                      // the creation of the file.
out.write(line);
out.close();
roro
  • 713
  • 2
  • 6
  • 19