1

在我的一项任务中,我试图读取文件并逐行打印。我尝试再次使用 hasNextLine 并没有用。我试图以某种方式完成它,但我想知道是否有某种方法可以在不创建新扫描仪的情况下再次浏览我的文件。

这是我的代码片段

sc = new Scanner(new File(args[0]));

        while (sc.hasNextLine()) {

            System.out.println(sc.nextLine());
        }

我想稍后再使用一段时间,但我不能这样做。有没有办法重置或将其带回顶部并再次遍历文件。

4

3 回答 3

1

You can just create a new Scanner after closing the first one:

sc.close();
sc = new Scanner(new File(args[0]));

// do the same thing again
于 2013-09-13T13:26:30.620 回答
0

您可以使用FileReader装饰 a RandomAccessFile

RandomAccessFile f = new RandomAccessFile(args[0], "r");
Scanner sc = new Scanner(new FileReader(f.getFD()));

//Read through scanner

//Rewind file
f.seek(0L);

//Read through file again
于 2013-09-13T13:30:55.633 回答
0

为了优化,您可以保存对文件的引用以供将来使用。

File f = new File(args[0]);
sc = new Scanner(f);
//...
sc = new Scanner(f);

Scanner 不是智能迭代器,因此创建新的成本可能比“倒带”旧的成本要小。

于 2013-09-13T13:29:50.050 回答