Sample Programs

Sample java program to read file

To execute this program successfully, you should have "sample.txt" file in C:\ location, otherwise an error will be thrown.

 package org.jusfortechies.example; 

 import java.io.BufferedReader;
 import java.io.DataInputStream;
 import java.io.FileInputStream;
 import java.io.InputStreamReader;
 import java.io.IOException;
 import java.io.FileNotFoundException;

 public class ReadFile {

     public static void main(String args[]) {
       
	   try{
	     // Open the file 
	     FileInputStream fin = new FileInputStream("C:\\samplefile.txt");

	     // Get the object of DataInputStream
	     DataInputStream in = new DataInputStream(fin);
	     BufferedReader br = new BufferedReader(new InputStreamReader(in));
	     
		 String line;
	     
		 //Read File line by line and print the line
	     while ((line = br.readLine()) != null)   {
	        System.out.println (line);
	     }

	     //Close the input stream
	     in.close();

	   }catch (FileNotFoundException e) {
	     System.err.println("Error: " + e.getMessage());
	   } catch (IOException e) {
	     System.err.println("Error: " + e.getMessage());
	   }

	}

 }



blog comments powered by Disqus