簡體   English   中英

將多行用戶輸入寫入文件

[英]Writing Multiple Lines of User Input to a File

我試圖通過讀取用戶的輸入,直到達到某個終止符序列,在控制台中擁有一個等效的文本框,但是我無法弄清楚如何使其終止。

這里應該讀取輸入並將其寫入文件的代碼:

try {
    out = new BufferedWriter(new FileWriter("outagain.txt");
    userInput = new Scanner(System.in);

    String input;
    while ((input = userInput.nextLine)) != null) {
        out.write(input);
        out.newLine();
        input = null;
    }
} finally {
    if (userInput != null)
        userInput.close();
    if (out != null)
        out.close();

有什么方法可以捕獲用戶的轉義“代碼”(即,他們寫出“:END”,它會跳出循環)還是有另一種方法?

先感謝您。

您可以通過將每個輸入行與特定的終止字進行比較來實現。 假設終止詞為:END那么我們可以用termination word檢查每條輸入線。

如果我們發現該終止詞作為輸入,我們將中斷循環並停止從用戶那里獲取輸入,並關閉BufferedReaderScanner

樣例代碼:

    try 
    {
        out = new BufferedWriter(new FileWriter("outagain.txt"));
        userInput = new Scanner(System.in);

        String input = userInput.nextLine();    //Store first input line in the variable
        String Termination_Word = ":END";
        while(!input.equals(Termination_Word))  //Everytime Check it with the termination word.
        {
            out.write(input);                   //If it isnot a termination word, Write it to the file.
            out.newLine();
            input=userInput.nextLine();         //Take other line as an input.
        }
    } 
    finally 
    {
        if (userInput != null)
            userInput.close();
        if (out != null)
            out.close();
    }

暫無
暫無

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

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