Saturday 23 June 2012

Reading and writing binary files in Java

Byte streams are generally designed to deal with "raw" data (like image file,mp3 etc.) from a file or stream.A byte stream access the file byte by byte. A byte stream is suitable for any kind of file, however not quite appropriate for text files. For example, if the file is using a Unicode encoding and a character is represented with two bytes, the byte stream will treat these separately and you will need to do the conversion yourself.


Byte streams are implemented by the java.io.InputStream and java.io.OutputStream classes and their subclasses.We can use java.io.FileInputStream and java.io.FileOutputStream classes for reading and writing binary file.


Example

 1) Copy an Image file using FileInputStream and FileOutputStream

The following code reads an image file mca1.png using FileInputStream and copies it using FileOutputStream.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyImage {

    /**
     * @param args
     * @throws IOException
     **/
    public static void main(String[] args) {
        FileInputStream fin = null;
        FileOutputStream fout = null;

        try {
            fin = new FileInputStream("/home/radhakrishnan/Desktop/img.png");
            fout = new FileOutputStream("/home/radhakrishnan/Desktop/img_copy.png");
            int ch;
            while ((ch = fin.read()) != -1) {
                fout.write(ch);
            }
            System.out.println("Image copy completed");
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            try {
                fin.close();
                fout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


The output is

Image copy completed


Buffered Byte Streams


The above example uses unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.

To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as abuffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

A program can convert an unbuffered stream into a buffered stream, where the unbuffered stream object is passed to the constructor for a buffered stream class. There are two buffered stream classes used to wrap unbuffered byte streams: BufferedInputStream and BufferedOutputStream create buffered byte streams.

Example

 2) Copy an Image file using BufferedInputStream and BufferedOutputStream


The following code reads an image file img.png using BufferedInputStream and copies it using
BufferedOutputStream.

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyImageUsingBuffer {

 /**
  * @param Pass
  * @throws IOException
  **/
 public static void main(String[] args) {
  BufferedInputStream in = null;
  BufferedOutputStream out = null;
  int b;
  try {
   in = new BufferedInputStream(new FileInputStream(
     "/home/radhakrishnan/Desktop/img.png"));
   out = new BufferedOutputStream(new FileOutputStream(
     "/home/radhakrishnan/Desktop/img1.png"));

   while ((b = in.read()) != -1) {
    out.write(b);
   }

  } catch (IOException e) {
   System.out.println(e);
  } finally {
   try {
    in.close();
    out.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

}

No comments:

Post a Comment