2

My question is, whether it is direct use, as shown below;

class Test{    
public static void main(String args[]){       
  try{ 
    FileWriter fo =new FileWriter("somex.txt"); 
    int arr[] = {9}; 
    for(int i =0; i <arr.length; i++){
      fo .write(arr[i]); // this is very costly.
    }
    fo.write(b); 
    fo.close(); 
    System.out.println("....");
 }catch(Exception e){system.out.println(e);}     
 } 
}    

OR

coding it more efficient as shown below;

class Test{     
 public static void main(String args[])throws Exception{  
   BufferedWriter bfw= new BufferedWriter(new FileWriter("foo.out")));  

   int arr[] = {9};
   for(int i =0; i <arr.length; i++){
      bfw .write(arr[i]); 
    }

   bfw.flush();  
   bfw.close();  

   System.out.println(".......");  
 }  
}   

There is no difference because both will do same write operation. Can someone help me understand the subtleness?

MKod
  • 803
  • 5
  • 20
  • 33
  • 1
    The buffered writer won't write until it reaches it's buffer size...This allows for less writes and io operations are costly so if i write 1 time compared to you writing 10 times the 1 write will be better... – brso05 Jun 03 '15 at 15:31
  • 1
    http://stackoverflow.com/questions/14462705/how-does-bufferedwriter-work-in-java – brso05 Jun 03 '15 at 15:31

1 Answers1

1

The BufferedWriter will store the contents in memory until it reaches it's buffer size then it will do one big write vs. writing directly each time for FileWriter. So with the FileWriter every iteration of your loop there will be a write. The BufferedWriter may only write once at the end of your loop depending on your buffer size.

brso05
  • 13,142
  • 2
  • 21
  • 40