Tuesday, December 13, 2011

java program to read a text file

This is the java program to read a text file and it writes to the command prompt. We use fileinputstream to read a text file. The read() function extracts the ascii value of each character in a file. We have to convert that ascii value into its original form. First we have to take the sample text document in any folder but we have to declare the path of text document.

/*  java program to read a text file */
 import java.io.*;
class readfile
{
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;

try {
 fin = new FileInputStream("C:/sampath/sample.txt"); //You give your text file path
 }
catch(FileNotFoundException e) {
 System.out.println("File Not Found");
 return;
 }

 catch(ArrayIndexOutOfBoundsException e) {
 System.out.println("Usage: ShowFile File");
 return;
 }

do {

i =fin.read();
if(i!=-1)
System.out.print((char)i);
} while(i!=-1);

}
}




Output: