Search code examples
javafilewriter

Basic String editing with FileWriter


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

Solution

  • 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()