Monday, 3 June 2013

Java File and IO : DataOutputStream

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:

Using DataOutputStream in writing boolean data type

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataOutputStreamWriteBoolean {
   public static void main(String[] args) {
      String file = "C://tutorialpointph//booleanfile.txt";    
      try
      {
  //create the file booleanfile
  FileOutputStream fos = new FileOutputStream(file);
      
  /*    
  * DataOutputStream(OutputStream os) constructor.   
  */
      
  DataOutputStream dos = new DataOutputStream(fos);      
  boolean b = true; //One byte of data
      
  /*
  * writeBoolean() methods writes the boolean to output 
  * as a byte if true. If false, no byte is present.
  */
        
   dos.writeBoolean(b);
       
   System.out.println("boolean byte has been written.");
   dos.close();
        
      }  
      catch (IOException e)
      {
   System.out.println("IOException : " + e);
      }
   }
}

Using DataOutputStream in writing byte data type

0 comments:

Post a Comment