Search code examples
javafilenewlineprintstream

How to append new line in an existing file?


How am I supposed to append a new line after I finish adding what I am supposed to. I have the following code:

        try{
            String textToAppend = question+userInput+","+typeOfAnswer;
            Files.write(Paths.get("save.txt"), textToAppend.getBytes(), StandardOpenOption.APPEND);
        }
        catch (NoSuchFileException e){

        }
        catch(IOException e){

        }

Example: question: By what initials was Franklin Roosevelt better known? userInput: RED typeOfAnswer will be wrong: wrong

I get my question and real answer from a file, then I compare the real answer with the userInput and see whether the typeOfAnswer si wrong/right. I want to output the question, userInput and typeOfAnswer in a File but I have multiple questions, hence I want to output the final results each on a new line.


Solution

  • As commented:

    textToAppend += System.lineSeparator();
    

    Proof

    import java.nio.file.*;
    
    public class Test {
        public static void main(String[] args) throws Exception {
            save("By what initials was Franklin Roosevelt better known?", "RED", "wrong");
            save("Which number president was Franklin Roosevelt?", "RED", "wrong");
        }
        public static void save(String question, String userInput, String typeOfAnswer) throws Exception {
            String textToAppend = question + userInput + "," + typeOfAnswer;
            textToAppend += System.lineSeparator();
            Files.write(Paths.get("save.txt"), textToAppend.getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);
        }
    }
    

    File Content

    By what initials was Franklin Roosevelt better known?RED,wrong
    Which number president was Franklin Roosevelt?RED,wrong
    

    File Content after running program 3 times

    By what initials was Franklin Roosevelt better known?RED,wrong
    Which number president was Franklin Roosevelt?RED,wrong
    By what initials was Franklin Roosevelt better known?RED,wrong
    Which number president was Franklin Roosevelt?RED,wrong
    By what initials was Franklin Roosevelt better known?RED,wrong
    Which number president was Franklin Roosevelt?RED,wrong