Monday, October 11, 2010

Reading data from file (Java)

In this post, I am explaining about how to read data from the file.


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

public class fileDemo {

fileDemo f = new fileDemo() ;

public static void main(String args[]) {
try {
// opening the file and creating a command line argument
FileInputStream fstream = new FileInputStream("file_name.txt") ;
//Creating a object for the data input stream
DataInputStream in = new DataInputStream(fstream) ;
BufferedReader br = new BufferedReader(new InputStreamReader(in)) ;
String sdata = null ;
while ((sdata = br.readLine()) != null) {
System.out.println(sdata) ;
// checking if the line read is the start of the record or not
}
in.close() ;
}
catch (Exception e) {
e.getMessage() ;
}
}

}

The class path can be given at the unless the file that has to be read is present in the same location as the program.

The file format can be of any type that is read by a word editor.

No comments:

Post a Comment