Monday, April 15, 2013

Java IO vs NIO

Java NIO (New IO) was introduced in JDK 1.4. While Java IO centralizes around Stream/Reader/Writer and uses decorator pattern as its main design, where you have decorate one InputStream type with each other in the right order. The NIO uses Channel/Buffer/Selector.

Read a file using IO


File file =new File("C:\\test\\test.txt");
FileInputStream  fis = new FileInputStream(file);

//decorate BufferedReader with InputStreamReader
BufferedReader d = new BufferedReader(new InputStreamReader(fis));
String line=null;
while((line = d.readLine()) != null){
         System.out.println(line);
}

Read a file using NIO

RandomAccessFile rFile = new RandomAccessFile("C:\\test\\test.txt", "rw");
   
//get Channel
FileChannel inChannel = rFile.getChannel();
   
//Intialize byte buffer
ByteBuffer buf = ByteBuffer.allocate(100);
   
//read data to buffer
while(inChannel.read(buf)>0){
 buf.flip(); //flip into read mode
 while(buf.hasRemaining()){
  System.out.print((char)buf.get());
 }
 buf.clear();
    
}
rFile.close();

5 comments:

  1. Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete
  2. It should be noted that whilst ordering papers for sale at paper writing service, you can get unkind attitude. In case you feel that the bureau is trying to cheat you, don't buy term paper from it. r&b musica italian

    ReplyDelete
  3. Your Affiliate Money Making Machine is ready -

    Plus, making money online using it is as simple as 1 . 2 . 3!

    Here's how it works...

    STEP 1. Choose affiliate products the system will promote
    STEP 2. Add PUSH BUTTON TRAFFIC (it LITERALLY takes JUST 2 minutes)
    STEP 3. See how the affiliate products system explode your list and sell your affiliate products all on it's own!

    Are you ready??

    Click here to launch the system

    ReplyDelete