如何为目录java中的每个文件创建一个新的bufferedreader

时间:2016-08-19 14:33:43

标签: java

我在目录中有一堆文件,我想同时阅读所有这些文件。 在我的代码中,他将逐个阅读所有文件。

public void OptimiserListeDesTermes(String repertoireToFileTermes) throws IOException {

    File dir = new File(repertoireToFileTermes);

    if (dir.isDirectory()) {

        File[] list = dir.listFiles();
        String nameFich = "";
        if (list != null) {

            for (int i = 0; i < list.length; i++) {

                nameFich = list[i].getPath();

                FileReader filereader = new FileReader(ReadPath(nameFich));

                BufferedReader reader = new BufferedReader(filereader);

            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这样的事情:

public void OptimiserListeDesTermes(String repertoireToFileTermes) throws IOException {
    File dir = new File(repertoireToFileTermes);
    if (dir.isDirectory()) {
        File[] list = dir.listFiles();
        if (list != null) {
            Arrays.stream(list).filter(f -> f.isFile() && f.canRead()).parallel().forEach(file -> {
                try {
                    BufferedReader reader = new BufferedReader(new FileReader(file));
                    ...
                } catch (FileNotFoundException ex) {
                    // log the error
                }
            });
        }
    }
}

或者喜欢这个?

public void OptimiserListeDesTermes(String repertoireToFileTermes) throws IOException {
    File dir = new File(repertoireToFileTermes);
    if (dir.isDirectory()) {
        File[] list = dir.listFiles();
        if (list != null) {
            int buffers = 0;
            BufferedReader[] readers = new BufferedReader[list.length];
            for (File file : list) {
                if (file.isFile() && file.canRead()){
                    readers[buffers++] = new BufferedReader(new FileReader(file));
                }

            }
            readers = Arrays.copyOf(readers, buffers);                

            // do something with readers
        }
    }
}