Sunday 27 November 2022

Read file content using BufferedReader in Java

Step 1: Get the instance of FileReader.

final FileReader fileReader = new FileReader(filePath);

 

Step 2: Get the instance of BufferedReader from FileReader.

final BufferedReader bufferedReader = new BufferedReader(fileReader);

 

Step 3: Read the file content using read method of BufferedReader.

final StringBuilder stringBuilder = new StringBuilder();
final char[] charBuffer = new char[65535];
int noOfCharsRead;

while ((noOfCharsRead = bufferedReader.read(charBuffer)) != -1) {
	stringBuilder.append(charBuffer, 0, noOfCharsRead);
}

 

Find the below working application.


FileUtil.java

package com.sample.util;

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

public class FileUtil {

	public static String readText(final String filePath) throws FileNotFoundException, IOException {
		if (filePath == null || filePath.isEmpty()) {
			return "";
		}

		try (final FileReader fileReader = new FileReader(filePath);
				final BufferedReader bufferedReader = new BufferedReader(fileReader)) {

			final StringBuilder stringBuilder = new StringBuilder();

			final char[] charBuffer = new char[65535];

			int noOfCharsRead;
			while ((noOfCharsRead = bufferedReader.read(charBuffer)) != -1) {
				stringBuilder.append(charBuffer, 0, noOfCharsRead);
			}
			return stringBuilder.toString();
		}
	}

}

FileReadDemo.java

package com.sample.app;

import java.io.IOException;

import com.sample.util.FileUtil;

public class FileReadDemo {

	public static void main(final String[] args) throws IOException {
		final String filePath = "/Users/Shared/a.txt";

		System.out.println(FileUtil.readText(filePath));
	}

}

 

You may like

file and stream programs in Java

How to download a binary file in Java?

How to process a huge file line by line in Java?

How to get the directory size in Java?

Convert string to InputStream in Java

Read the data from BufferedReader in Java

No comments:

Post a Comment