简体   繁体   中英

Reading multiple text files from directory line by line JAVA

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?

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

}

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.

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 should still go through the tutorial, but this will get you started for this purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM