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

时间:2018-10-17 20:51:32

标签: java eclipse hashmap bufferedreader readfile

    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映射作为键:单词和值的长度为数组List。

我面临的问题是我的程序第一次读取文件,但不再读取同一文件。我尝试使用mark()和reset()函数,但再次遇到相同的问题。您可以看到输出的理由。我该如何解决这个问题?

我的程序输出是: 文件中的最大字长:22
HashMap键:1的包数:26 ///(表示在第1个整数中找到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

2 个答案:

答案 0 :(得分:3)

相对于处理内存中的数据,从磁盘读取是一项昂贵的操作,因此您只应读取一次文件。我建议您做这样的事情:

    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 );
        }
    }

答案 1 :(得分:0)

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");
            }
        }
    }
}