How to Java programming- Read File

In Java, you can use java.io.BufferedReader to read content from a file. There are many ways to read file, but this BufferedReader is the simplest and most common-used method. Here is a simple Java program that reads a text file line by line and displays each line on the console using System.out.println.

 

Read a Java File

Here is a simple Java program that reads a text file line by line and displays each line on the console using System.out.println.

Read File
	package read_file;
	import java.io.BufferedReader;
	import java.io.FileReader;
	import java.io.IOException;
	public class Demo {

		public static void main(String[] args) {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader("C:\\Path\\to\\file\\fileName.txt"));
			String line;			
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {				
				e.printStackTrace();
			}
		}
		}
	}

 

Here is a program that loads the contents of a text file into a String by reading each line and concatenating the results using StringBuilder.

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

	//A simple example program that reads into a String using StringBuilder.

	 public class ReadTextFileExample {
		 public static void main(String[] args) {
			 StringBuilder sb = new StringBuilder();
			 BufferedReader br = null;
			 try {
				br = new BufferedReader(new FileReader("C:\\temp\\testfile.txt"));
				String line;
				while ((line = br.readLine()) != null) {
				   if (sb.length() > 0) {
				   sb.append("\n");
				   }
				sb.append(line);
				}
			 } catch (IOException e) {
				e.printStackTrace();
			 } finally {
				try {
				  if (br != null) {
					 br.close();
				  }
				} catch (IOException ex) {
				  ex.printStackTrace();
				}
			 }
			 String contents = sb.toString();
			 System.out.println(contents);
		 }
	}

 

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...