簡體   English   中英

如何使用BufferedReader一次又一次地讀取相同的txt文件?

[英]How to read same txt file again and again using BufferedReader?

    String fileName="words.txt"; //words.txt file contains 25,000 words
    String word;

    try {

    FileReader fileReader=new FileReader(fileName);
    BufferedReader bufferReader;

    ArrayList<String> arrBag;

    int count;
    bufferReader=new BufferedReader(fileReader);

    for (int i=1;i<=maxWordLength;i++)  //maxWordLength is 22
    {
        arrBag = new ArrayList<String> (); // arrBag contains all words with same length and then store to hash map.

        count=0;

        bufferReader.mark(0);               
        while((word=bufferReader.readLine())!=null)
        {
            if (word.length()==i)
            {
                arrBag.add(word);
                count++;
            }
        }

        System.out.println("HashMap key : "+i+" has bag count : "+count);
        mapBagOfTasks.put(Integer.toString(i), arrBag);  //mapBagOfTasks is HashMap where key is length of word and value is ArrayList of words with same length.   

        bufferReader.reset();

    }
    if (fileReader!=null)
    {
        fileReader.close();
    }



}
catch (FileNotFoundException e) {
    System.out.println("Input file not found");
    e.printStackTrace();
}
catch (IOException e) {
    System.out.println("Error while reading File '"+fileName+"'");
    e.printStackTrace();
}

我有一個包含25,000個單詞的“ words.txt”文件。 我想將所有具有相同長度的單詞存儲到ArrayList中,然后將其存儲為Hash映射作為鍵:單詞和值的長度為數組列表。

我面臨的問題是我的程序第一次讀取文件,但不再讀取同一文件。 我嘗試使用mark()和reset()函數,但再次遇到相同的問題。 您可以看到輸出的理由。 我該如何解決這個問題?

我的程序輸出是:文件中的最大單詞長度:22
HashMap鍵:1的包數:26 //(意味着找到第1個lenth中有26個單詞)
HashMap鍵:2,包數:0
HashMap密鑰:3的包數:0
HashMap鍵:4,包數:0
HashMap鍵:5的包數:0
HashMap密鑰:6的包數:0
HashMap密鑰:7的包數:0
HashMap密鑰:8的包數:0
HashMap密鑰:9的包數:0
HashMap密鑰:10的包數:0
HashMap鍵:11的包數:0
HashMap鍵:12的包數:0
HashMap鍵:13的包數:0
HashMap鍵:14的包數:0
HashMap鍵:15的包數:0
HashMap鍵:16的包數:0
HashMap鍵:17的包數:0
HashMap密鑰:18,包數:0
HashMap密鑰:19的包數:0
HashMap密鑰:20,包數:0
HashMap鍵:21的包數:0
HashMap密鑰:22的包數:0

相對於處理內存中的數據,從磁盤讀取是一項昂貴的操作,因此您只應讀取一次文件。 我建議你做這樣的事情:

    Map<Integer, List<String>> lengthToWords = new HashMap<>();
    while ((word = bufferReader.readLine()) != null) {
        int length = word.length();
        if (length < maxWordLength) {
            if (!lengthToWords.containsKey( length ))
                lengthToWords.put( length, new ArrayList<>() );
            lengthToWords.get( length ).add( word );
        }
    }

IO通常是所有程序中最慢的部分。 除非處理的文件大於可用的ram大小,否則應將整個文件讀入ram一次,然后在該文件上進行操作。 根據您對要執行的操作的描述,這就是我要編寫的代碼。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class WordLength {

    public static void main(String[] args) {

        String fileName = "words.txt";
        int maxWordLength = 0;

        HashMap<Integer, ArrayList<String>> mapBagOfTasks = new HashMap<>();

        // populate the HashMap
        try {
            BufferedReader br = new BufferedReader(new FileReader(fileName));

            String word = "";
            while ((word=br.readLine())!=null) {

                int count = word.length();
                if (count>maxWordLength) {
                    maxWordLength = count;
                }

                // if an array list for words of length count is not in the map. put in a new one
                if (!mapBagOfTasks.containsKey(count)) {
                    mapBagOfTasks.put(count, new ArrayList<>());
                }

                // get the array list for words of length count
                ArrayList<String> arrBag = mapBagOfTasks.get(count);

                // add word to that array list
                arrBag.add(word);

            }

            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // loop over all of the keys and their values
        for (int key=0; key<maxWordLength; key++) {
            if (mapBagOfTasks.containsKey(key)) {
                ArrayList<String> value = mapBagOfTasks.get(key);

                System.out.println("HashMap key : "+key+" has bag count "+value.size());
            } else {
                System.out.println("HashMap key : "+key+" has bag count 0");
            }
        }
    }
}

暫無
暫無

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

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