Monday, 3 June 2013

Java File and IO: BufferedOutputStream

There are a lot of APIs regarding files and IO in Java. Some of the basics will be discussed here.

  1. BufferedInputStream
  2. BufferedOutputStream
  3. DataInputStream
  4. DataOutputStream
First let us differentiate all these.

1. BufferedInputStream :  kind of inputStream that buffers the input data in order to optimize the speed access to the data.

2. BufferedOutputStream : kind of outputStream that buffers bytes.

3. DataInputStream : is a kind of InputStream used to read data as primitive data types from an underlying input stream.

4.DataOutputStream : kinf of outputStream that allows user to write data as primitive data types.

Examples:

BufferedOutputStream

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferedOutputStreamExample {
 public static void main(String[] args) {
  String file = "C://tutorialpointph//file.txt";
  BufferedOutputStream bos = null;
         
        try
        {
            //Get the file to write data to 
            FileOutputStream fos = new FileOutputStream(file);
                 
            /*
             * creates a BufferedOutputStream          
             */  
            bos = new BufferedOutputStream(fos);
                 
            char a = 'a';  
            bos.write(a);
            System.out.println("Char 'a' has been written.");
         }
         catch(FileNotFoundException e){
             System.out.println("File not found on path" + e);
         }
         catch(IOException ie){
             System.out.println("Exception while writing" + ie);
          }
         finally
         {
              try
              {
                 if(bos != null)
                 {
                    bos.flush();
                    bos.close();
                 }
               }
               catch(Exception e){}
         }
 }
}

0 comments:

Post a Comment