Google

May 16, 2013

Java I/O Interview Questions and Answers

Java I/O interview questions are popular with some interviewers, especially the job you are applying for requires file processing. The Java NIO (stands for New I/O) package was introduced in Java version 4 and NIO2 was released in Java version 7.

Q. Why do you need to favor NIO (i.e. New I/O) to old I/O?
A.  A stream-oriented I/O (or old I/O) deals with data one byte at a time. An input stream produces one byte of data, and an output stream consumes one byte of data. It is very easy to create filters and chain several filters together so that each one does its part in what amounts to a single, sophisticated
processing mechanism. On the flip side, stream-oriented I/O is often rather slow.

A block-oriented I/O system deals with data in blocks. The New I/O consumes a block of data in one step. Processing data by the block can be much faster than processing it by byte (i.e. streamed). But block-oriented I/O lacks some of the elegance and simplicity of stream-oriented I/O.


The examples below read the content of this file and print it to a console. In reality, you can do whatever you want once you have read it like mapping to Java POJOs, etc.

Q. Can you describe different ways in which you can read data from a file?
A. Files can be read a number of ways. Here is a sample file named person.csv in a folder c:\temp\tlm.

FirstName, Surname, Age
John,Smith, 35
Peter,John, 28
Shirley,John,34


1. The I/O way using a BufferedReader


package com.arul;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * This is a slower way using the old io
 */
public class ReadFileOldIOWay
{ 
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = null;
        String sCurrentLine = null;
        try
        {
            br = new BufferedReader(
                    new FileReader("c:/temp/tlm/person.csv"));
            while ((sCurrentLine = br.readLine()) != null)
            {
                System.out.println(sCurrentLine); // for demo only. use log.info(...) instead
            }
        }
        catch (IOException e)
        {
            e.printStackTrace(); // quick & dirty for demo only
        }
        finally
        {
            if (br != null)
            {
                br.close();
            }       
        }
    }
}



2. The nio way using a ByteBuffer for smaller files

package com.arul;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * This is using the nio ByteBuffer for smaller files
 */
public class ReadFileWithByteBuffer
{
    public static void main(String args[]) throws IOException
    {
        RandomAccessFile aFile = null;
        try
        {
            aFile = new RandomAccessFile(
                    "c:/temp/tlm/person.csv", "r");
            FileChannel inChannel = aFile.getChannel();
            long fileSize = inChannel.size();
            ByteBuffer buffer = ByteBuffer.allocate((int) fileSize);
            inChannel.read(buffer);//read the first header line
            buffer.flip();//The limit is set to the current position
            while (buffer.hasRemaining())
            {
                System.out.print((char) buffer.get()); // for demo only. use log.info(...) instead 
            }
            
            inChannel.close();
            
        }
        catch (IOException exc)
        {
            exc.printStackTrace(); //quick & dirty for demo only
            System.exit(1);
        }
        finally
        {
            aFile.close();
        }
    }
}



3. The nio way using a ByteBuffer with chunking for larger files


package com.arul;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * This is using the nio ByteBuffer chunking for larger files
 */
public class ReadFileWithByteBufferInChunksForLargerFiles
{
    public static void main(String args[]) throws IOException
    {
        RandomAccessFile aFile = null;
        try
        {
            aFile = new RandomAccessFile(
                    "c:/temp/tlm/person.csv", "r");
            FileChannel inChannel = aFile.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(18);
            while (inChannel.read(buffer) > 0)
            {
                
                buffer.flip();
                while (buffer.hasRemaining())
                {
                    System.out.print((char) buffer.get()); // for demo only. use log.info(...) instead
                }
                buffer.clear();
            }
            
            inChannel.close();
            
        }
        catch (IOException exc)
        {
            exc.printStackTrace(); //quick & dirty for demo only
            System.exit(1);
        }
        finally
        {
            aFile.close();
        }
    }
}


4. The nio way using a MappedByteBuffer for better performance, but beware of the file size

package com.arul;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * This is a faster way using the nio MappedByteBuffer
 */

public class ReadFileWithMappedByteBufferWay
{
    public static void main(String[] args) throws IOException
    {
        RandomAccessFile aFile = null;
        
        try
        {
            aFile = new RandomAccessFile
                    ("c:/temp/tlm/person.csv", "r");
            FileChannel inChannel = aFile.getChannel();
            MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
            buffer.load();
            for (int i = 0; i < buffer.limit(); i++)
            {
                System.out.print((char) buffer.get()); // for demo only. use log.info(...) instead
            }
            buffer.clear(); // do something with the data and clear/compact it.
            inChannel.close();
        }
        finally
        {
            aFile.close();
        }
    }
}


The output for all the above alternatives is

FirstName, Surname, Age
John,Smith, 35
Peter,John, 28
Shirley,John,34


The nio package is very efficient as it uses buffering and non blocking I/O with selectors compared to the old I/O.

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home