Showing posts with label File Reading in Java. Show all posts
Showing posts with label File Reading in Java. Show all posts

Saturday, September 17, 2016

Java program to read file contents

The below Java program will read the contents from a file line by line and will print it in the screen


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFromFile {
public static void main (String args[]) {

  StringBuffer sFileContents = new StringBuffer();
  try (BufferedReader br = new BufferedReader(new FileReader("C:\\myfile.txt")))
  {
   String sCurrentLine;

   while ((sCurrentLine = br.readLine()) != null) {
    sFileContents.append(sCurrentLine);
   }
  } catch (IOException ex) {
   ex.printStackTrace();
   throw ex;
  }
  System.out.println("File content is :"+sFileContents);
 }
}