0

I have 2 Strings that I want to add to a txt File. The first String needs to be in the first Line, the second one in the second line. The "\n" command seems not to work, because in my output file both Strings are in one line.

    FileWriter writer = new FileWriter(measurements);
    String text1 = x.measurementToString(x);
    String text2 = z.measurementToString(z);
    writer.write(text1 + "\n" + text2);
    writer.close();
    System.out.println("Strings added to file!");
skonline90
  • 53
  • 7

3 Answers3

1

Since the new line character is different in different OSes, you can use System.getProperty("line.separator") to get newline char for the operating system at runtime.

For Java 7 you can also use System.lineSeparator()

suvartheec
  • 3,484
  • 1
  • 17
  • 21
0

Maybe you are on windows and opening the file with a tool that does not recognise \n as a line separator, such as notepad?

File I/O is easier with the methods in the Files class. In your case:

Path p = Paths.get("C:/path/to/your/file/filename.ext");
//or
Path p = measurements.toPath();

Files.write(p, Arrays.asList(text1, text2), StandardCharsets.UTF_8);

This will use the default line separator on your computer and should solve your issue.

assylias
  • 321,522
  • 82
  • 660
  • 783
0

Use PrintWriter.println() instead.

It must be something like that:

try (PrintWriter writer = new PrintWriter(file)) {
    writer.println(text1);
    writer.println(text2);
}
D. Braun
  • 508
  • 1
  • 4
  • 11