【问题标题】:Read files from directory using BufferedReader使用 BufferedReader 从目录中读取文件
【发布时间】:2021-06-24 14:37:04
【问题描述】:

我编写了一个代码来从目录中读取文件。 该目录包含许多文件。首先,我计算目录中的文件数,然后我想计算文件中扩展名为.info.data的行数

我的代码如下:

   public void checkEmptyEntryFileLoader(String directory) {
        File name = new File(directory);
        String filenames[]=name.list();
        long countFile = 0;
        long countLineData = 0;
        long countLineInfo = 0;

        for(String filename:filenames){
            //System.out.println(filename);
            countFile++;
        }
        System.out.println(countFile); // this bloc worked well

        File files[]=name.listFiles();
        for(File file:files){
            String fileName = file.getName();
            if(fileName.endsWith("data")) {
                try {
                    BufferedReader reader = new BufferedReader(new FileReader(fileName));
                    while (reader.readLine() != null) {
                        countLineData++;
                    }
                }catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

             if(fileName.endsWith("info")) {
                try {
                    BufferedReader reader = new BufferedReader(new FileReader(fileName));
                    while (reader.readLine() != null) {
                        countLineInfo ++;
                    }
                }catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(countLineInfo );

        }
    }

我得到了错误:

java.io.FileNotFoundException: my_file_name.data (No such file or directory)
        at java.io.FileInputStream.open0(Native Method)
        at java.io.FileInputStream.open(FileInputStream.java:195)
        at java.io.FileInputStream.<init>(FileInputStream.java:138)
        at java.io.FileInputStream.<init>(FileInputStream.java:93)
        at java.io.FileReader.<init>(FileReader.java:58)

错误涉及the FileReader,它只接受string,而filenameString

你有什么想法吗? 谢谢

【问题讨论】:

标签: java bufferedreader filereader


【解决方案1】:

不要在FileReader() 中传递filename,而是尝试传递file

BufferedReader reader = new BufferedReader(new FileReader(file));

我的回答假设您作为输出给出的错误是在 try-catch 块中打印的堆栈跟踪,而不是您尝试编译/运行代码时遇到的错误。

【讨论】:

    【解决方案2】:

    @SARVESH TANDON 的回答看起来可以解决您的问题,并注意您扫描文件系统两次。

    考虑使用 NIO 和流来扫描大型文件系统,因为 File.list / File.listFiles 在文件数量变大时性能非常差,或者您需要进行更深入的扫描,因为它们需要重复。

    这是使用 NIO 的代码示例。它使用过滤器将搜索限制为仅具有正确扩展名的文件,您可以将 find depth=1 参数更改为 Integer.MAX_VALUE 以进行深度扫描,并处理异常:

    Path dir = Path.of(directory);
    long[] counts = new long[3]; // FILES, MATCHFILES, LINECOUNT
    try(Stream<Path> stream = Files.find(dir, 1, (p, a) -> ++counts[0] > 0 && a.isRegularFile())) {
        stream.filter(p -> { String fn = p.getFileName().toString();
            return (fn.endsWith("data") || fn.endsWith("info"))  && ++counts[1] > 0; })
        .forEach(p -> {
            try(Stream<String> lines = Files.lines(p)) {
                long count = lines.count();
                counts[2]+=count;
                System.out.println("path: "+p+" lines:"+count);
            } catch (IOException io) {
                throw new UncheckedIOException(io);
            }
        });
    }
    System.out.println("Total files: "+(counts[0]-1));  // dir is counted too
    System.out.println("Match files: "+counts[1]);
    System.out.println("Total lines: "+counts[2]);
    

    【讨论】:

      猜你喜欢
      • 2017-08-12
      • 2017-12-01
      • 2013-04-12
      • 2014-03-08
      • 2015-04-22
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多