【问题标题】:Java Scanner pointer issue between static methods静态方法之间的 Java Scanner 指针问题
【发布时间】:2019-02-15 23:18:08
【问题描述】:

我的扫描仪对象有问题。如果我将扫描仪传递给静态方法,扫描仪似乎无法读取它在主函数中给出的文件。当我将文件对象传递给扫描仪,然后将扫描仪传递给 Add 函数时,它不会将文件内容输出到控制台。但是,如果我注释掉 Add 函数的扫描仪部分,扫描仪会正常读取。这使我相信扫描仪能够看到文件,但不能从中读取。我的问题是如何再次读取文件,这次是在 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());
    }

}

【问题讨论】:

    标签: java java.util.scanner


    【解决方案1】:

    你不能那样做。一旦通过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();
    }
    

    【讨论】:

    • 这是有道理的,但是使用我现在的设置,即使我只从 Add() 读取文件,它仍然不会打印任何内容。好像文件里什么都没有。就好像当我将扫描仪传递给 Add() 时,扫描仪读取文件的能力消失了。
    • @VincentTomie 查看更新后的答案。我解释了发生了什么。
    • 是的,您刚刚为我回答了核心问题,即为什么它不扫描。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多