添加完我应该添加的内容后,我应该如何添加新行。 我有以下代码:
try{
String textToAppend = question+userInput+","+typeOfAnswer;
Files.write(Paths.get("save.txt"), textToAppend.getBytes(), StandardOpenOption.APPEND);
}
catch (NoSuchFileException e){
}
catch(IOException e){
}
示例:问题:富兰克林·罗斯福以哪个名字缩写更广为人知? userInput:RED typeOfAnswer将是错误的:错误
我从文件中获取问题和真实答案,然后将真实答案与userInput进行比较,看看typeOfAnswer是否错误/正确。我想在文件中输出问题userInput和typeOfAnswer,但是我有多个问题,因此我想将最终结果每个都输出到新行中。
答案 0 :(得分:3)
评论如下:
textToAppend += System.lineSeparator();
证明
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);
}
}
文件内容
By what initials was Franklin Roosevelt better known?RED,wrong
Which number president was Franklin Roosevelt?RED,wrong
运行程序3次后的文件内容
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