>

Saturday, December 15, 2012

Java I\O Part I

Input and output process are the most common things for making the application which need external data, fortunately java provide package java.io. In Java 1(version 1.0), input and output process was based on byte-oriented. It means all I/O, process was in byte form, Java version 1.1 was released, process for I/O can be manipulated by character-oriented forms too, the process more easier than byte-oriented.

Java process I/O through stream, stream was abstraction for put or obtain information. Stream can be connected to physical tools such as keyboard, file, console screen or socket. Event all tools were connected were different but how the stream work is always the same for input and output process.

Stream can use byte stream or character stream. Byte stream is used for put or retrieve data information in form byte, such as read or write file for binary file, whereas character stream is used in form character, such as for processing write and read to file texts, stream character uses Unicode character.


A. Byte Streams
I will to show how byte stream work , A program can read or write any file one byte at a time with the help of one of the subclasses of InputStream or OutputStream respectively.
For example writing a file, we Make a file with extension “. dat”.

First we make datas will be put in our file say our data is “example.dat”., what kind data you see bellow,

int[] datas = {56,230,123,43,11,37,11};

and than we import FileOutputStream from package java.io

FileOutputStream fileOutputStream = null;

the full code you see below :


import java.io.FileOutputStream;

public class ByteStreamWrittingDemo {

  public static void main(String[] args) {

     int[] datas = {56,230,123,43,11,37,11};
     FileOutputStream fileOutputStream = null;

     try {
         fileOutputStream = new FileOutputStream("example.dat");
        // start for writing to a file
         for (int i = 0; i < datas.length; i++) {
           fileOutputStream.write(datas[i]);
        }
     } catch (Exception e) {
       System.out.println(e.toString()); 
     }finally{
       // to close process so all data will be in "example.dat"
      if(fileOutputStream != null){
      try {
          fileOutputStream.close();
      } catch (Exception e2) {
          e2.printStackTrace();
        }
       }
     }
   }
}


every time you finished writing file datas to the new file don’t forget to close process as you see the code above.
If we open the file has been created the file will look like this :
shabbynote open file created
open the file that has been created


now we will make how to read binary file in java. We will use the file that we have created before,
For reading file in java, java has class FileInputStream. We can use straight use chunk code bellow

FileInputStream  input =newFileInputStream("example.dat");
int data = input .read();



our chunk code above well it isn’t recommended because reading file one byte at the time, In general, disk access is much slower than the processing performed in memory, that’s why it’s not a good idea to access disk a thousand times to read a file of 1000 bytes. To minimize the number of times the disk is accessed, Java provides so-called buffers, which serve as reservoirs of data. Here the chucnk of code

FileInputStream input = new FileInputStream("example.dat");
BufferedInputStream buffer =new BufferedInputStream(input );



The class BufferedInputStream works as a middleman between FileInputStream and the file itself. It reads a big chunk of bytes from a file into memory in one shot, and the FileInputStream object then reads single bytes from there, which is memory-to-memory operations. BufferedOutputStream works similarly with the class FileOutputStream. The main idea here is to minimize disk access.
in process reading file in java after finish read whole content file will return value “-1”, this fact sometimes is used for terminating iteration in reading file process.

the full code you will see bellow

import java.io.BufferedInputStream;
import java.io.FileInputStream;

public class ByteStreamReadDemo {
  public static void main(String[] args) {
   FileInputStream input = null;
   BufferedInputStream buffer = null;
   try {
    input = new FileInputStream("example.dat");
    buffer = new BufferedInputStream(input);

    boolean stopIterate = false;
    while (!stopIterate) {
      int byteValue = buffer.read();
      System.out.print(byteValue +" ");
      if(byteValue == -1){
        stopIterate =true;
       }
    }
   } catch (Exception e) {
    System.out.println(e.toString());
  }finally{
    if(input != null){
      try {
         buffer.close();
         input.close();
       } catch (Exception e2) {
       // TODO: handle exception
        e2.printStackTrace();
        }
     }
   }
  }
}

 

While reading a stream with the help of BufferedInputStream you watch for the end-of-file character. But when you write a stream via BufferedOutputStream with method write(), you need to do one extra step. Call the method flush() before closing the buffered stream. This ensures that none of the buffered bytes “get stuck” and that all are written out to the underlying output stream. 
You might be wondering, how large is the buffer? While the default buffer size varies depending on the OS, you can control it using a two-argument constructor. For example, to set the buffer size to 5000 bytes instantiate the buffered stream as BufferedInputStream buff = new BufferedInputStream(myFile, 5000);

No comments:

Post a Comment