Read all files inside folder in java code by using FileInputStream and BufferReader classes.

Create File object by passing obsolete folder path and read all files using listFiles() method.

File folder = new File(folderPath);
File[] listOfFiles = folder.listFiles();

Create BufferReader object as below

//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(streamReader);

Iterate through each line by using bufferReader.readLine() method.
 
Complete class FolderRead.java can be found below;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FolderRead {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// Call method readFolder
		readFolder("C:/temp/FolderName");
	}
	
	public static void readFolder(String folderPath) throws IOException
	{
		File folder = new File(folderPath);
		File[] listOfFiles = folder.listFiles();
		BufferedReader bufferReader = null;
		
		for (File file : listOfFiles) {
		    if (file.isFile()) {
		        System.out.println(file.getPath());
		        try{
		          InputStream inputStream = new FileInputStream(file.getPath()); 
		          InputStreamReader streamReader = new InputStreamReader(inputStream);

		          //Instantiate the BufferedReader Class
		          bufferReader = new BufferedReader(streamReader);

		          //Variable to hold the each line data
		          String line;

		          // Read file line by line...
		          while ((line = bufferReader.readLine()) != null)   {
			        	System.out.println(line);
			        	line = line.trim();
		          }
		       }catch (Exception e) {
				e.printStackTrace();
			   }finally{
				   bufferReader.close();
			   }
		    }
		}
	}
}

For further reading refer Java Programming Category posts.

Share this post

How to read all files inside folder in java code
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *