JAVA 从目录中逐行读取多个文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18994754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:11:40  来源:igfitidea点击:

Reading multiple text files from directory line by line JAVA

javafiletextdirectory

提问by bluiejoe

Could someone give me an example of how you could read in a directory of text files and read each text file line by line using Java?

有人能给我一个例子,说明如何使用 Java 在文本文件目录中读取并逐行读取每个文本文件?

So far I have:

到目前为止,我有:

    String files;
    File folder = new File(file_path);
    File[] listOfFiles = folder.listFiles(); 

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

       if (listOfFiles[i].isFile())  {

                // do something here??
            }
      }

回答by arcy

In the Java javadocs, look up FileReader, then BufferedReader -- the first reads a file, the second takes a reader as a constructor parameter and has a readline() method.

在 Java javadocs 中,查找 FileReader,然后是 BufferedReader —— 第一个读取文件,第二个将读取器作为构造函数参数并具有 readline() 方法。

I agree this is a poor question, but file I/O is difficult to discern without some guidance, and the tutorials often spend too much time with things that you don't need for this purpose. You shouldstill go through the tutorial, but this will get you started for this purpose.

我同意这是一个糟糕的问题,但是如果没有一些指导,文件 I/O 很难辨别,而且教程通常会花费太多时间在您不需要的东西上。您仍然应该阅读本教程,但这将使您开始为此目的。

回答by 7stud

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.File;


public class MyProg {

    public static void main(String[] args) throws IOException {
        String target_dir = "./test_dir";
        File dir = new File(target_dir);
        File[] files = dir.listFiles();

        for (File f : files) {
            if(f.isFile()) {
                BufferedReader inputStream = null;

                try {
                    inputStream = new BufferedReader(
                                    new FileReader(f));
                    String line;

                    while ((line = inputStream.readLine()) != null) {
                        System.out.println(line);
                    }
                }
                finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            }
        }
    }

}