Sunday, 24 April 2016

How to read files in Java ?


Example
Using BufferedInputStream and DataInputStream

File file = new File("C:\\readFile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;

try {
  fis = new FileInputStream(file);
  bis = new BufferedInputStream(fis);
  dis = new DataInputStream(bis);
  while (dis.available() != 0) {
    System.out.println(dis.readLine());
  }

  fis.close();
  bis.close();
  dis.close();
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();

}


Example
Using BufferedReader
try {
  String sCurrentLine;
  BufferedReader br = 
       new BufferedReader(new FileReader("C:\\readFile.txt"));

  while ((sCurrentLine = br.readLine()) != null) {
    System.out.println(sCurrentLine);
  } 
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.