Input/Output In Java(Scanner, BufferedReader & Self Made Fast I/O)

I/O is most important part of any programming language. Java has many ways to take input & post output. As from the title I am here to discuss about above three types of Input & Output.

  1. Scanner
  2. Scanner is used to take formatted input as it break it into tokens and then parse that tokens into respective data types. It tokenize the string on the basis of Whitespaces by default which is space character. It is not synchronized so it is not thread-safe means multiple threads can produce unwanted results(refer Producer Consumer Problem). It usually parse the input which makes it slow and it have Buffer equals to 1K(1024bytes).It is simple than other I/O classes and a part of java.util package. Let us understand by example:-

    class HackTheJava
    {
        public static void main(String[] args)
        {
            Scanner sc=new Scanner(System.in);    //Instantiation Of Scanner Object
            int a=sc.nextInt();          //reads integer
            double b=sc.nextDouble();    //reads double
            String str=sc.nextLine();    //reads String
        }
    }
    
  3. BufferedReader
  4. Since Unbuffered I/Os reads input which is handled by underlying Operating System. This is slow because each time it have to trigger disk access. To remove such overhead buffered I/O introduced in java. Buffer is memory in which data is to be stored. It is faster the Scanner as it reads whole input as String through readLine() method and then we have to parse it into their respective data types. It is also Thread-safe.

    class HackTheJava
    {
        public static void main(String[] args)throws IOException
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            String str=br.readLine();    //reads String like 10<enter>
            int a=Integer.parseInt(str)          //reads integer
        }
    }
    

    Buffered Reader by default throws IOException which has to catch or throws further.

  5. Fast I/O
  6. Above I/O are great but slow and it is too slow as I will show you later.Here you have to create your own buffer and read input from InputStream directly through read(byte[] b) method. Let us understand directly by example:-

    class Scan
    {
    	private byte[] buf=new byte[1024];    //Buffer of Bytes
    	private int index;
    	private InputStream in;
    	private int total;
    	public Scan()
    	{
    		in=System.in;
    	}
    	public int scan()throws IOException    //Scan method used to scan buf
    	{
    		if(total<0)
    		throw new InputMismatchException();
    		if(index>=total)
    		{
    			index=0;
    			total=in.read(buf);
    			if(total<=0)
    			return -1;
    		}
    		return buf[index++];
    	}
    	public int scanInt()throws IOException
    	{
    		int integer=0;
    		int n=scan();
    		while(isWhiteSpace(n))    //Removing starting whitespaces
    		n=scan();
    		int neg=1;
    		if(n=='-')                //If Negative Sign encounters
    		{
    			neg=-1;
    			n=scan();
    		}
    		while(!isWhiteSpace(n))
    		{
    			if(n>='0'&&n<='9')
    			{
    				integer*=10;
    				integer+=n-'0';
    				n=scan();
    			}
    			else throw new InputMismatchException();
    		}
    		return neg*integer;
    	}
    	private boolean isWhiteSpace(int n)
    	{
    		if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
    		return true;
    		return false;
    	}
    }
    

    In above method scan() we reading input as bytes through read(byte[] b) method and return each Byte by increasing index. Then scanInt() return the inputted Integer.
    Similarly for output you can use BufferedWriter.

    class Print
    {
    	private final BufferedWriter bw;
    	public Print()
    	{
    		this.bw=new BufferedWriter(new OutputStreamWriter(System.out));
    	}
    	public void print(Object object)throws IOException
    	{
    		bw.append(""+object);
    	}
    	public void println(Object object)throws IOException
    	{
    		print(object);
    		bw.append("\n");
    	}
    	public void close()throws IOException
    	{
    		bw.close();
    	}
    }
    

    Now Check how fast is above method, Kindly see below link.
    http://www.codechef.com/status/FROGV,shivamsharma
    First One & two is showing the least time in which above method is used with little difference. Third One is when reading input with Scan object but output with OutputStream Object. And Fourth one is reading input from Scan object and outputting by System.out.println(). And using BufferedReader & Scanner you will get Time Limit Exceed(TLE) error.

Leave a comment