In the previous post, we have seen FileInputStream and FileOutputStream. In this post, we will look at BufferedInputStream and BufferedOutputStream in java.
Let’s start with BufferedOutputStream class.
BufferedOutputStream class:
BufferedOutputStream class uses an internal buffer to store the data first. Rather than writing one byte at a time to the destination file, stored data in a buffer will be written at a time. It is not required to make a system call for each byte written, hence speed up writing.
This is typically much faster , can be used for disk access and large amount of data. To add buffering to outputStream , simply add it through BufferedOutputStream. Let’s look at the example below for understanding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class FileHandlingEx { public static void main(String[] args){ try { FileOutputStream fout=new FileOutputStream("Sample.txt"); BufferedOutputStream bfrout=new BufferedOutputStream(fout); String s="My laptop is working good"; byte b[]=s.getBytes(); bfrout.write(b); bfrout.flush(); bfrout.close(); fout.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Write task successful"); } } |
BufferedInputStream:
BufferedInputStream class is used to provide buffering to inputStream. Instead of reading one byte at a time, it can read a large block of data. It improves the reading performance.
Example of BufferedInputStream:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class FileHandlingEx { public static void main(String[] args){ try{ FileInputStream fin=new FileInputStream("Sample.txt"); BufferedInputStream bin=new BufferedInputStream(fin); int i; while((i=bin.read())!=-1){ System.out.println((char)i); } bin.close(); fin.close(); }catch(Exception e){ System.out.println(e); } } } |
1 Response
[…] the previous post, we have seen BufferedInputStream and BufferedOutputStream. In this post, we will CharArrayWriter […]