File buffering is a mechanism where the data is read/written into a buffer memory area rather than directly on to disk. This hugely improves the I/O performance when reading or writing files large files since the application doesn't have to wait for the disk read or write to finish. File buffering is implemented in Java using four streams - BufferedInputStream, BufferedOutputStream, BufferedReader and BufferedWriter. The difference between these buffered streams are BufferedInputStream and BufferedOutputStream are byte streams while BufferedReader and BufferedWriter are character streams. Byte streams read and write data of 8-bit size each at a time. Characters streams are used specifically for character data as it converts the data to local character set. Here is two example programs that shows file read and write using buffered streams.
File copy using Buffered streams
This program copies the file named file1.txt to another file named file1_copy.txt using BufferedInputStream and BufferedOutputStream classes. The program creates a buffered input stream with the source file and a buffered output stream with the destination file. Input stream is read byte by byte and written to the output stream inside a while loop until EOF is reached. Any bytes that remain on the output buffer should be flused out to the disk and the the input and output streams are closed inside a finally block.
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class BufferedFileIO { public static void main(String[] args) throws IOException { BufferedInputStream bis = null; BufferedOutputStream bos = null; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream("file1.txt"); bis = new BufferedInputStream( fis); fos = new FileOutputStream("file1_copy.txt"); bos = new BufferedOutputStream(fos); int b; while ((b = bis.read()) != -1) { bos.write(b); } bos.flush(); } catch(IOException ex) { System.err.println(ex.getMessage()); } finally { if(fis!=null) fis.close(); if(bis!=null) bis.close(); if(fos!=null) fos.close(); if(bos!=null) bos.close(); } } }
Output text file to console
In this second example the program creates a buffered character input stream for the UTF-8 encoded text file named Japanese.txt, reads each charaacter until EOF and prints the characters to the console.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedFileIO2 { public static void main(String[] args) throws IOException { BufferedReader br = null; FileReader fr =null; try { fr = new FileReader("japanese.txt"); br = new BufferedReader(fr); int c; while ((c = br.read()) != -1) { System.out.print((char)c); } } catch(IOException ex) { System.err.println(ex.getMessage()); } finally { if(fr!=null) fr.close(); if(br!=null) br.close(); } } }