我的扫描仪对象有问题。看来,如果我将扫描仪传递给静态方法,则扫描仪将无法读取在main函数中提供的文件。当我将文件对象传递到扫描仪,然后将扫描仪传递到“添加”功能时,它不会将文件内容输出到控制台。但是,如果我注释掉“添加”功能的扫描仪部分,则扫描仪将正常读取。这使我相信扫描仪能够看到文件,但无法读取文件。我的问题是这次如何在Add函数中第二次从文件读取?

public static void main(String[] args) throws IOException
{
    File file = new File("vinceandphil.txt");

    if (file.createNewFile())
    {
        System.out.println("New file was created");
    }
    else {
        System.out.println("File already exists");
    }
    Scanner sc = new Scanner(file);

    FileWriter writer = new FileWriter(file);
    writer.write("Test data\n");
    Add(file, writer, sc);
    writer.close();

    while (sc.hasNextLine())
    {
        System.out.println(sc.nextLine());
    }

    sc.close();

}

public static void Add(File f, FileWriter w, Scanner scanner) throws IOException
{

    if (f.exists())
    {
        w.write("Got em coach\n");
        w.write("We need more info\n");
        w.write("Come again\n");
    }

    while (scanner.hasNextLine())
    {
        System.out.println(scanner.nextLine());
    }

}

最佳答案

你不能这样做。一旦通过nextLine()读取了一行,它就会被“扔掉”,并且指针将指向下一行。

要从文件开头重新开始,您必须实例化另一个Scanner

final Scanner yourNewScanner = new Scanner(file);


如果您想使用一种方法来移动文件,请查看RandomAccessFile



您指出的是Scanner没有打印出任何内容。
这是因为您没有在要求Scanner读取之前关闭文件流。

if (f.exists())
{
    w.write("Got em coach\n");
    w.write("We need more info\n");
    w.write("Come again\n");

    // Adding this call flushes and closes the data stream.
    w.close();
}

关于java - 静态方法之间的Java Scanner指针问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54718278/

10-13 03:30