Sunday 27 November 2022

Read the data from BufferedReader in Java

BufferedReader class read the text from a character-input stream. As it read the characters into a buffer, it is very efficient while reading the file data.

 

Find the below working application.


 

IOUtil.java

package com.sample.util;

import java.io.BufferedReader;
import java.io.IOException;

public class IOUtil {

	public static String readText(final BufferedReader bufferedReader) throws IOException {

		if (bufferedReader == null) {
			return "";
		}

		final StringBuilder stringBuilder = new StringBuilder();

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

		try {
			int noOfCharsRead;
			while ((noOfCharsRead = bufferedReader.read(charBuffer)) != -1) {
				stringBuilder.append(charBuffer, 0, noOfCharsRead);
			}
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException e) {
				System.out.println("Failed to close the reader : " + e.getMessage());
			}
		}
		return stringBuilder.toString();
	}

}

FileReadDemo.java

package com.sample.app;

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

import com.sample.util.IOUtil;

public class FileReadDemo {

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

		System.out.println(IOUtil.readText(bufferedReader));
	}

}



You may like

file and stream programs in Java

Write byte array to a file

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

No comments:

Post a Comment