Signup/Sign In

How to read multiple text files in Java

In this post, we are going to read multiple text files by using the Java code. It is helpful when we are working on a large project that requires to read data from multiple resources.

Here, we are using a File class that is used to handle the file-related operations in Java.

To read the multiple files, there can be several scenarios but here, we are reading files from a folder or two separate located files.

For sample purposes, we have two files file1.txt and file2.txt that are located into a folder filefolder. These two files contain some data that is given below.

// file1.txt

The default port for mysql is 3306

//file2.txt

Oracle db is running at port 8080

Example:

Let's take an example to read multiple files using the Java code. Here, we have a folder contains the two files that we will read. We used File class to get file instances and BufferReader class to read the file data.

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

public class Main {
	public static void main(String[] args) throws IOException{  
        File dir = new File("filefolder");
        File[] files = dir.listFiles();
        // Fetching all the files
        for (File file : files) {
            if(file.isFile()) {
                BufferedReader inputStream = null;
                String line;
                try {
                    inputStream = new BufferedReader(new FileReader(file));
                    while ((line = inputStream.readLine()) != null) {
                        System.out.println(line);
                    }
                }catch(IOException e) {
                	System.out.println(e);
                }
                finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            }
        }
        
	}
}


The default port for mysql is 3306
Oracle db is running at port 8080

Live Example:

Try this live example where we have two separate text files outside the folder and reading them. You can edit these text files to check whether the code produces the desired result.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.