簡體   English   中英

如何在Java中每次從不同的偏移量讀取大塊的String大文件?

[英]How to read a large file of Strings in chunks, each time from different offset, in Java?

我有一個包含幾行的大文件,其中每一行實際上是一個英語單詞。 完整的文件不適合內存。 因此,我想逐塊處理它。 因此,我需要實現以下內容:

  1. 方法1:讀取一個塊,調用方法2。
  2. 方法2:對該塊中的字符串進行一些處理,然后返回步驟1。

我有兩個問題。

1.如何實現Method1? 我非常了解如何實現Method2。

我知道如何使用BufferedReader逐行讀取大文件。 例如,

BufferedReader br = new BufferedReader(new FileReader(file)) {
    String line;
    while ((line = br.readLine()) != null) {
       // process the line.
    }

但是我想讀更多的行而不是一行,並在Method2中處理所有這些行。 然后,當我回到Method1時,我想再次加載幾行...

2.我的假設是,處理一行代碼比處理每一行更為有效(從性能角度而言)。 這個假設正確嗎?

BufferedReader有效地負責讀取塊中的行。

因此,實際上您的選擇是:

  • 在每次調用readLine()之后,調用您的方法進行處理
  • 在每次調用readLine()之后,將行添加到列表中,然后每次列表達到某個大小時,調用您的方法來處理列表,然后將其清除

因此,主要因素是您的“處理”實際上所做的事情:一次在多行上運行該流程在邏輯上是否有意義,並且如果一次傳遞多行,該處理方法是否可以包含某種優化?

這只是基礎編程,如果您想閱讀多於1行的內容,請這樣做。

void method1(java.io.File file) throws IOException {
        int n = 10; // Number of lines to read
        BufferedReader br = new BufferedReader(new FileReader(file));
        List<String> lines;
        do {
            lines = readNLines(br, n);
            method2(lines);
        } while (!lines.isEmpty());
    }

    public void method2(List<String> lines) {
        // processing...
    }

    private List<String> readNLines(BufferedReader reader, int numberOfLines) throws IOException {
        List<String> lines = new ArrayList<>(numberOfLines);
        String line;
        while (lines.size() < numberOfLines && ((line = reader.readLine()) != null)) {
            lines.add(line);
        }
        return lines;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM