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



我正在尝试将一些文本写入文件。我有一段时间循环,应该只需带一些文本并将完全相同的文本写回文件。

我发现,由于扫描仪认为没有更多的文本可以阅读,因此从未输入过循环。但是有。

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);

它删除了您的文件。

您正在尝试使用扫描仪读取文件并使用printwriter编写另一个文件,但是两个都在同一文件上工作。printWriter清除文件的内容以编写内容。课程需要在不同的文件上工作。

最新更新