簡體   English   中英

如何在現有文件中添加新行?

[英]How to append new line in an existing file?

添加完我應該添加的內容后,我應該如何添加新行。 我有以下代碼:

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

        }
        catch(IOException e){

        }

示例:問題:富​​蘭克林·羅斯福以哪個名字縮寫更廣為人知? userInput:紅色typeOfAnswer將是錯誤的:錯誤

我從文件中獲取問題和真實答案,然后將真實答案與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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM