Sunday, September 30, 2007

File Handling: Reading from a File

To read input data, by default we use the computer keyboard. However, some of the data we need maybe stored in some data file. For example, if you have a class record stored in a file and you want to retrieve it, or simply want to read a text file using your java program.


Reading from a file:

The FileInputStream class allows you to read data from a file.

The class has the following constructors:

o FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.

o FileInputStream(FileDescriptor fdObj)
Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.

o FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

(Descriptions taken from http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileInputStream.html)


Let’s try the FileInputStream class.


First, create a text file and save it in the same directory where you create the class.


Second, try this code:

/**
* @(#)ReadFile.java
*
* @JEDI Phase II Course Material
* @With comments insertions from
* @ erlyn manguilimotan
*/

import java.io.*;

public class ReadFile {

public static void main(String args[]){

BufferedReader fileRead = new BufferedReader (new InputStreamReader(System.in));
String fileName = "";
System.out.println("Enter the name of the file to Open");
try{
fileName=fileRead.readLine(); //input the name of the file
}catch(IOException e1){
}//end of catch

FileInputStream rf = null; //create an object for FileInputStream

try{
rf = new FileInputStream(fileName); //connects the object with the file name
}catch(FileNotFoundException e2){
System.out.println("File not found...");
}//end of catch

try{
char data; //variable to hold the data
int temp=0;
do{
temp=rf.read(); // Reads a byte of data from this input stream.
data = (char) temp; //stores the data into variable data
if(temp!=-1) //while it's not the end of file
{
System.out.print(data);
}
}while(temp!=-1); //ends the loop if it's the end of file.

}catch(IOException e3){
System.out.println("Problem in reading the file..");
}//end of catch
} //end of main
}//end of class

Compile and execute the code.

NOTE! Make sure you have a text file to open! You may want to use the following contents for your text file:

Hello World!
This is a sample file to be read by a java file.
How does the output appear on your screen?

*******************************************************************************

No comments: