How to read contents of File in Java?

We can read the contents of a file using two techniques, first is reading contents using DataInputStream and another is
BufferedReader.

Reading contents using DataInputStream:

DataInputStream makes easier to read integer, float, double data and other primitive data types without needing to interpret if the read data should be an integer or double etc.


DataInputStream in = null;
BufferedReader br = null;
try{


FileInputStream fileInputStream = new FileInputStream("C:\\test7.txt" );
// Getting the object of DataInputStream
in = new DataInputStream( fileInputStream );
br = new BufferedReader(new InputStreamReader(in));
String strLine;

while ((strLine = br.readLine()) != null) {

System.out.println (strLine);
}

}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{

if( in != null){
try{

in.close();
}catch(IOException es){

}
}
if( br != null){
try{

br.close();
}catch(IOException es){

}
}
}


Reading the file contents using BufferedReader :


BufferedReader is used to read text from a character-input stream, it buffers characters to provide for the efficient reading of characters, Strings and Arrays. As seen in example below we use FileReader object to pass to the BufferedReader and calling readLine() method on BufferedReader object to read the line.


BufferedReader in = null;
try {
in = new BufferedReader( new FileReader( "C:\\test7.txt" ));
String line = null;
while ( (line = in.readLine()) != null) {
writer.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if (in != null)
in.close();
} catch (Exception exp) {
}
}
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment