Read File Using Java BufferedInputStream Example. This example shows how to read a file using available and read methods of Java BufferedInputStream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
import java.io.*; public class app { public static void main(String[] args) { //create file object File file = new File("C://ReadFile.txt"); BufferedInputStream bin = null; try { //create FileInputStream object FileInputStream fin = new FileInputStream(file); //create object of BufferedInputStream bin = new BufferedInputStream(fin); /* * BufferedInputStream has ability to buffer input into * internal buffer array. * * available() method returns number of bytes that can be * read from underlying stream without blocking. */ //read file using BufferedInputStream while( bin.available() > 0 ){ System.out.print((char)bin.read()); } } 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); } } } } /* Output: File content */ |