0
votes

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.

1
What exception you get? - Emre Savcı
textToAppend += System.lineSeparator(); - Andreas
@EmreSavcı I'm not getting any exceptions but if I try let's say to create the textToAppend like this: textToAppend = "\n"+question+userInput+","+typeOfAnswer I won't get the new information in a new line. - Ryk
@Andreas tried..i have the same problem..i get sth like this: By what initials was Franklin Roosevelt better known?RED,wrongWhich number president was Franklin Roosevelt?RED,wrong. There is no separation between wrong and Which - Ryk
@Ryk Are you on Windows, using Notepad to show file content? If so, then be aware that Notepad doesn't recognize \n as an end-of-line marker. Only \r\n. - Andreas

1 Answers

3
votes

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