Blog Archive

Java Read File using BufferedInputStream example

package com.as400samplecode;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadBufferedInputStream {

 public static void main(String[] args) {

  File file = new File("data/newFile.txt");
  FileInputStream fis = null;
  BufferedInputStream bis = null;
  
  try {
   fis = new FileInputStream(file);
   bis = new BufferedInputStream(fis);

   //process each character at a time
   while( bis.available() > 0 ){
    System.out.print((char)bis.read());
   }

  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    fis.close();
    bis.close();
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  }

 }

}


Another more efficient way using a byte array
package com.as400samplecode;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadBufferedInputStream {

 public static void main(String[] args) {

  File file = new File("data/newFile.txt");
  FileInputStream fis = null;
  BufferedInputStream bis = null;

  try {
   fis = new FileInputStream(file);
   bis = new BufferedInputStream(fis);

   byte[] buffer = new byte[1024];
   int bytesRead = 0;

   // Keep reading from the file while there is any content
   // when the end of the stream has been reached, -1 is returned
   while ((bytesRead = bis.read(buffer)) != -1) {
    // Process the chunk of bytes read
    // in this case we just construct a String and print it out
    String chunk = new String(buffer, 0, bytesRead);
    System.out.print(chunk);
   }

  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    fis.close();
    bis.close();
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  }

 }

}