恢复读取 Java 中的巨大文本文件

Resume read of huge text file in Java

我正在阅读一个巨大的单词文本文件(每行一个单词),但我不得不时不时地停下来以便第二天继续阅读。现在我正在使用 Apache 的 lineiterator 但它是完全错误的解决方案。我的文件是 7Gb,我不得不在 1Gb 时中断读取它。为了恢复阅读,我保存了已阅读的行数。这意味着我在 while 循环中有一个 if 语句。 Apache 的 FileUtils 不允许搜索,所以这是我的解决方案。

best/fastest 解决方案是什么?我想使用 RandomAccessfile 转到正确的行并继续阅读,但我不确定我是否可以转到正确的位置以及如何保存我最后阅读的正确位置。我可以再读几行,所以精度不是那么重要,但我还没有找到获取指针的方法。我有一个 BufferedReader 来读取文件和一个 RandomAccessFile 来寻找正确的位置,但我不知道如何使用 BufferedReader 定期保存位置。 有什么提示吗?

代码:(注意 "SOMETHING" 我应该打印我可以在 seekToByte 上使用的值的地方)

try {

        RandomAccessFile rand = new RandomAccessFile(file,"r");
        rand.seek(seekToByte);
        startAtByte = rand.getFilePointer();
        rand.close();

    } catch(IOException e) {
        // do something
    }

    // Do it using the BufferedReader 
    BufferedReader reader = null;
    FileReader freader = null;
    try {
        freader = new FileReader(file);
        reader = new BufferedReader(freader);
        reader.skip(startAtByte);

        long i=0;
        for(String line; (line = reader.readLine()) != null; ) {

            lines.add(line);
            System.out.print(i+" ");
            if (lines.size()>1000) {
                commit(lines);
                System.out.println("");
                lines.clear();
                System.out.println(SOMETHING?);
            }
        }

    } catch(Exception e) {
        // handle this           
    } finally {
        if (reader != null) {
            try {reader.close();} catch(Exception ignore) {}
        }
    }

RandomAccessfile 确实是一种方法。使用

long position = file.getFilePointer();

当您停止阅读以保存您在文件中的位置,然后恢复时:

file.seek(position);

在同一个地方恢复阅读。

但是,使用RandomAccessfile时要小心,因为它的readLine方法不完全支持Unicode。

你能以某种方式使用预定的偏移量,例如将文件分成四块 (offset0, offset1) (offset1, offset2)..etc,并使用 RecursiveAction (ForkJoin API) 来利用并行性.