>
Showing posts with label InputStreamReader. Show all posts
Showing posts with label InputStreamReader. Show all posts

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);

Java I\O Part II

In the previous post we have try how byte streams process, now we continue for character oriented, how it work same but have different class.

A. Character Streams
Text in java presented as set char which values two-byte characters, based on unicode standard, some of the standard charsets are US-ASCII, UTF-8, and UTF-16. The Java classes FileReader and FileWriter were specifically created to work with text files, but they work only with default character encoding and don’t handle localization properly. According the best way is to pipe class InputStreamReader with specified encoding and the FileInputStream then InputStreamReader reads bytes and decodes them into characters using a specified CharSet, for FileOutputStream and OutputStreamWriter are same treatment as FileInputStream. The class InputStreamReader .

Let’s try for writing a text file, we determine what we will put in our text file :

String myWrting ="Hi guys! This is my file text"

we use FileOutputStream and OutputStreamWriter, I pipe The class FileOutputStream reads bytes and decodes them into characters using a specified CharSet. “UTF8”

FileOutputStream myFile = new FileOutputStream("myWrting.txt");
Writer out = new BufferedWriter(new OutputStreamWriter(myFile,"UTF8"));

and here its our full code,

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class WrittingTxtDemo {

public static void main(String[] args) {
 try {
 String myWrting ="Hi guys! This is my file text";
 FileOutputStream myFile = new FileOutputStream("myWrting.txt");

 Writer writer = new BufferedWriter(new  
 OutputStreamWriter(myFile, "UTF8"));

  writer.write(myWrting);
  writer.flush();
  writer.close();

  } catch (Exception e) {
      e.printStackTrace();
    }
  }
}



you may open the file we have created by notepad, and the contain will the same as we put in the code above.

Now we create how to read file text file in java, reads bytes from a text file and converts them from UTF-8 encoding into Unicode to return results as a String, I recommended uses StringBuffer that usually works faster than String when it comes to performing text manipulations. I used file that has been created before.


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class ReadingTxtDemo {
public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer();

  try {
    FileInputStream myFile = new FileInputStream("myWrting.txt");
    InputStreamReader input = new InputStreamReader(myFile,  
    "UTF8");
    Reader reader = new BufferedReader(input);
 
     int ch;
   
     while ((ch = reader.read())> -1) {
      buffer.append((char) ch);
     }

      buffer.toString();
      System.out.println("The file contains : "+buffer);
     } catch (Exception e) {
      System.out.println(e);
     }
   }
}

Part Java I\O Part |||

In this post, I will try how to make program that java response from console, what in my concern is no matter you put any kind type data in console such char, string, and Number, we always use the same class InputStreamReader and BufferedReader, the differences is how we manipulate that data capture from console. I will start from from simple for char type.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CharacterInputDemo {

  public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
   System.out.println("Please Input Random Character : ");
    char character;
    InputStreamReader input = new InputStreamReader(System.in);
    BufferedReader buffer = new BufferedReader(input);
     character = (char) buffer.read();
 
     System.out.println("Character \'"+character+"\'");
   }

}


as we see above our input was casting to char, because every time retrieve value from BufferedReader class the data type is integer, because we want in char type then we cast integer to char. Now I will show if we want capture string type from console ok, take look code bellow:


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class StringInputDemo {

public static void main(String[] args) throws IOException {
   System.out.println("what is your name ? ");
   String name;

   InputStreamReader input = new InputStreamReader(System.in);
   BufferedReader buffer = new BufferedReader(input);

   name = buffer.readLine();
   System.out.println("Hello, "+name+" nice too meet you !");
   }
}



as we see above we don’t have to casting from the input that we have put because BufferedReader class have method “readLine()” to capture from console and when we retrieve automatic in string form. Now I will show how to what if put number type like integer, check out the code bellow:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class NumberInputDemo {
  public static void main(String[] args) throws IOException {
   
  String temp;
  int a = 0;
  System.out.println("Pick a number please ? ");

  InputStreamReader input = new InputStreamReader(System.in);
  BufferedReader buffer = new BufferedReader(input);
  temp = buffer.readLine();

  try {
    a = Integer.parseInt(temp);
    System.out.println("the power 2 of your value "+a*a);

  }catch(NumberFormatException numberFormatException) {
  System.err.println("Data that you has put "+temp+"notnumber");
    }
  }
}
As we see above we capture value from console was same as we for string value, the difference is we convert to the format as we want and prevent if we put not in number form.

Thread Part I -Main Thread, Child thread and Method for Creating Thread

 Thread Part I
Main Thread, Child thread and Method for Creating Thread

Thread is part of program which is independent and can be run simultaneous, it mean a thread can be paused without to stop whole program. Every thread in java is inheritance from thread class in package java.lang. When we run java program in our program there will be at least one thread, this thread named main thread and the other thread named child thread .Let’s see how there is at least one thread in every time we run java program.

Here the full code :

public class MainThreadDemo {

public static void main(String[]args) throw InterruptedException{

  // retrieve the active thread
     Thread mainThread = Thread.currentThread();
     System.out.println("the default thread name :");
     System.out.println(mainThread.toString());
   // changing default thread name
     mainThread.setName("Main Thread");
     System.out.println("retrieve the new name for thread :");
     System.out.println(mainThread.toString());
     System.out.println("example for controlling thread");
     for (int i = 0; i < 5; i++) {
       System.out.println("delay..."+(i+1));
       Thread.sleep(1000);
     }
   }
}



the output when retrieving the default thread name
Thread[main,5,main] → [thread name, priority, group]
as how above that is the out format when we try current thread, main was the name of thread, the thread priority value is 5 and the group name is main.

For creating thread or child thread there are two method, first using interface and implements to the class that we made for thread,

public class MyRunnable implements Runnable{
@Override
   public void run() {
    System.out.println("the child thread is executed...");
   }
}


for running thread show bellow

public class MyRunnableDemo {
  public static void main(String[] args) {
    MyRunnable myRunnable = new MyRunnable();
    Thread thread = new Thread(myRunnable);
    thread.start();
    System.out.println("the main thread is executed...");
   }
}

if we run the result show bellow,

the main thread is executed...
the child thread is executed...

both method for running the thread we must call method start from thread itself, then automatic call run method for thread. We saw that the output both thread show that the program will execute main thread first and then the child thread.

Perhaps we confuse which one we should use, its depend on what you need, if we see in design side using interface is the best one, and also it is fit, if we just need runnable method only without override the from thread class, but if you need to modify every method in thread class extends thread class is the best way.

Thread Part II - Stop the Thread and MultiThreading in java


Thread Part II
Stop the Thread and MultiThreading in java

Every thread that has been executed will be stop after every code in run() is finished executed, method will be automatic stop, but it doesn’t mean we can’t stop thread every time we want, we can stop thread using method stop(), but this method not recommended because the method is deprecated, the best thing that we can do by using boolean variable for controlling looping process.
Let’s see the example,

public class MyThreadStop extends Thread {
   private boolean finish = false;

   public void run() {
      int counter = 0;
      System.out.println("the child thread is executed...");

      while (!finish) {
        System.out.print((++counter) + " ");
       }
       System.out.println("the child thread is ended ");
      } 
// method as flag trigger to stop looping, once this method is
// invoke
   public void stopThread() {
    finish = true;
   }
}

No matter what in method run looping or not, as long as we give flag to stop the method run(), we can stop our thread as we see the code bellow

public class MyThreadStopDemo {

public static void main(String[]args)throws InterruptedException{
  
  System.out.println("the main thread is executed...");
  MyThreadStop myThreadStop = new MyThreadStop();
  myThreadStop.start();
  Thread.sleep(25);
 // triggering method to stop child thread
  myThreadStop.stopThread();
  System.out.println("\nEnd main Thread ");
  
  }

}


for code above we see that we didn’t called stop() method belong to the thread we just call a method stop contain a flag for stopping process in run() method.

in java program we need more than one child thread, program that contain thread more than one child thread called multithreaded. To prove java can handle multithreading we create two threads and invoke the two threads in demo class.

First thread :
public class MyThreadOne extends Thread{
   public void run(){
     try {
       for (int i = 0; i <10 ; i++) {
            System.out.println("First thread : "+(i+1));
            if( i!= 9){
               sleep(1000);
             }else{
              System.out.println("First thread finish....\n");
              }
            }
    }catch (InterruptedException e) {
      e.printStackTrace();
    }
   }
}

second thread :

public class MyThreadTwo extends Thread{
   public void run(){
     try {
       for (int i = 0; i < 5 ; i++) {
           System.out.println("Second thread :"+(i+1));
           if( i!= 4){
             sleep(1000);
             }else{
             System.out.println("Second thread finish....\n");
            }
           }
     } catch (InterruptedException e) {
       e.printStackTrace();
      }
    }
}

now we will call both thread
public class MutipleThreadDemo {

   public static void main(String[] args) {
    MyThreadOne myThreadOne = new MyThreadOne();
    myThreadOne.start();
    MyThreadTwo myThreadTwo = new MyThreadTwo();
    myThreadTwo.start();
   }
}


and if we execute demo class the result as shown bellow


First thread : 1
Second thread : 1
Second thread : 2
First thread : 2
First thread : 3
Second thread : 3
Second thread : 4
First thread : 4
First thread : 5
Second thread : 5
Second thread finish....

First thread : 6
First thread : 7
First thread : 8
First thread : 9
First thread : 10
First thread finish....

 
we see the result the first five line has same value it showed thread were executed together, after the sixth second running, second thread finished. Because only five looping steps for second thread. as the result above java has multithreading feature.