简体   繁体   中英

How to read the content of all of the text files of a directory using Java?

My problem is that I want to iterate all the text files in a directory using Java but whenever I start for loop over files, it always results in half processing, like for example:- I have 80 files and I want to read content of each file then I start my loop, it executes only last half part of file. Note: I have tried FileInputStream, Scanner class, BufferedReader as well. In FileInputStream, it gives EOFException and half-iteration results for other two methods. Here is my code -

    package InputFiles;

    import java.io.*;
    import java.util.Scanner;

    public class FileInput {
    public static void main(String[] args)  {
    File folder=new File("C:\\Users\\erpra\\Downloads\\SomePath");
    File[] listOfFiles=folder.listFiles();
    BufferedReader br=null;
    try {
        for(File tempFile:listOfFiles){
            System.out.println(tempFile.getName());
            br=new BufferedReader(new FileReader(tempFile));
            String str;
            while ((str=br.readLine())!=null){
                System.out.println(str);
            }
        }

    }catch (IOException e){
        e.printStackTrace();
    }finally {
        try {
            br.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
   }
    }

Your code seems to work for me but I would suggest to manage the FileReader and BufferedReader differently:

public static void main(String[] args) {
    File folder=new File("C:\\Users\\erpra\\Downloads\\SomePath");
    File[] listOfFiles=folder.listFiles();
    try {
        for (File tempFile : listOfFiles) {
            System.out.println(tempFile.getName());
            try (FileReader fr = new FileReader(tempFile); 
                 BufferedReader br = new BufferedReader(fr);) 
            {
                String str;
                while ((str = br.readLine()) != null) {
                    System.out.println(str);
                }
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

By using try-with-resources every FileReader and BufferedReader will be closed properly at the end of the try block. You only close the last reader.

But as you can see I did not change the while loop as it should work fine this way.

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