在添加完我应该添加的内容后,我该如何添加新行。 我有以下代码:
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
我从文件中获取问题和真实答案,然后将真实答案与 userInput 进行比较,看看 typeOfAnswer 是否错误/正确。我想在文件中输出问题、userInput 和 typeOfAnswer,但我有多个问题,因此我想在新行中输出最终结果。
最佳答案
正如评论:
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
关于java - 如何在现有文件中追加新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53527542/