Read File in String Using BufferedInputStream - Java File Path IO

Java examples for File Path IO:BufferedInputStream

Description

Read File in String Using BufferedInputStream

Demo Code


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

public class Main {

  public static void main(String[] args) {

    // create file object
    File file = new File("C://Folder//ReadFile.txt");
    BufferedInputStream bin = null;

    try {//from www .j a v  a  2s  . c o  m
      // create FileInputStream object
      FileInputStream fin = new FileInputStream(file);

      // create object of BufferedInputStream
      bin = new BufferedInputStream(fin);

      // create a byte array
      byte[] contents = new byte[1024];

      int bytesRead = 0;
      String strFileContents;

      while ((bytesRead = bin.read(contents)) != -1) {

        strFileContents = new String(contents, 0, bytesRead);
        System.out.print(strFileContents);
      }

    } catch (FileNotFoundException e) {
      System.out.println("File not found" + e);
    } catch (IOException ioe) {
      System.out.println("Exception while reading the file " + ioe);
    } finally {
      // close the BufferedInputStream using close method
      try {
        if (bin != null)
          bin.close();
      } catch (IOException ioe) {
        System.out.println("Error while closing the stream :" + ioe);
      }

    }
  }

}

Result


Related Tutorials