Today we will look at java character stream writer. Standard implementation FileWriter class is used to write character stream into the underlying file system. FileWriter class provides API to write character by character, character array and String. BufferedWriter is a process stream used to decorate the IO stream FileWriter. The process stream BufferedWriter helps to reduce the real IO operation, BufferedWriter comes with standard buffer size 8192. We can pass in the size of the buffer on the time of instantiation based on the availability of main memory. BufferedWriter improve the performance of file writing with the help of in memory buffer that in turn reduce the IO operation.
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 66 |
package com.ourownjava.corejava.file; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; /** * * @author ourownjava.com * */ public class FileWriterExample { public static void main(String[] args) throws IOException { FileWriterExample fileWriter = new FileWriterExample(); fileWriter.write(); fileWriter.writeThruBuffer(); } private void write() throws IOException{ Writer fileWriter = null; try { long startTime = System.currentTimeMillis(); fileWriter = new FileWriter(new File("FileWriterExample.dat")); for(int i=1000000; i>0; i--){ fileWriter.write(i+" ,"); } System.out.println("Time Taken with out buffer : "+ (System.currentTimeMillis() - startTime)); } catch (IOException e) { e.printStackTrace(); } finally{ if(null != fileWriter){ fileWriter.close(); } } } private void writeThruBuffer() throws IOException{ Writer fileWriter = null; try { long startTime = System.currentTimeMillis(); fileWriter = new BufferedWriter(new FileWriter(new File("BufferedFileWriterExample.dat"))); for(int i=1000000; i>0; i--){ fileWriter.write(i+" ,"); } System.out.println("Time Taken with buffer : "+ (System.currentTimeMillis() - startTime)); } catch (IOException e) { e.printStackTrace(); } finally{ if(null != fileWriter){ fileWriter.close(); } } } } |
1 2 |
Time Taken with out buffer : 606 Time Taken with buffer : 436 |
Pingback: Writer V/S BufferedWriter in java. | Clean Java