簡體   English   中英

為什么Scanner的hasNext()方法最初為非空文本文件返回false?

[英]why is Scanner's hasNext() method initially returning false for a non-empty text file?

我正在嘗試將一些文本寫入文件。 我有一個while循環,應該只接收一些文本並將完全相同的文本寫回到文件中。

我發現從來沒有進入while循環,因為Scanner認為沒有更多的文本可供閱讀。 但是還有。

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class WriteToFile {

    public static void main(String[] args) throws FileNotFoundException {

        String whatToWrite = "";

        File theFile = new File("C:\\test.txt");

        Scanner readinput = new Scanner(theFile);

        PrintWriter output = new PrintWriter(theFile);

        while (readinput.hasNext()) { //why is this false initially?

            String whatToRead = readinput.next();

            whatToWrite = whatToRead;

            output.print(whatToWrite);
        }

        readinput.close();
        output.close();

    }

}

文本文件僅包含隨機單詞。 狗,貓等

當我運行代碼時,text.txt變為空。

還有一個類似的問題: https : //stackoverflow.com/questions/8495850/scanner-hasnext-returns-false ,它指向編碼問題。 我使用Windows 7和美國語言。 我可以找出文本文件的編碼方式嗎?

更新:

確實,正如Ph.Voronov所說,PrintWriter行會擦除文件內容! user2115021是正確的,如果使用PrintWriter,則不應處理一個文件。 不幸的是,對於我必須解決的任務,我只能使用一個文件。 這是我所做的:

import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class WriteToFile {

    public static void main(String[] args) throws FileNotFoundException {

        ArrayList<String> theWords = new ArrayList<String>();

        File theFile = new File("C:\\test.txt");

        Scanner readinput = new Scanner(theFile);

        while (readinput.hasNext()) {

            theWords.add(readinput.next());

        }

        readinput.close();

        PrintWriter output = new PrintWriter(theFile); //we already got all of
            //the file content, so it's safe to erase it now

        for (int a = 0; a < theWords.size(); a++) {
            output.print(theWords.get(a));
            if (a != theWords.size() - 1) {
                output.print(" ");
            }
        }

        output.close();

    }

}
PrintWriter output = new PrintWriter(theFile);

它會刪除您的文件。

您正在嘗試使用SCANNER讀取文件並使用PRINTWRITER寫入另一個文件,但是兩者都在同一個文件上。PRINTWRITER清除文件的內容以寫入內容。兩個類都需要在不同的文件上工作。

暫無
暫無

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

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