Re: datainput stream

From: Anthony Borla (ajborla_at_bigpond.com)
Date: 12/09/03


Date: Tue, 09 Dec 2003 06:06:07 GMT


"Amey Samant" <ameyas7@yahoo.com> wrote in message
news:669e50b8.0312082105.77e0cae2@posting.google.com...
> hi all
>
> I was trying to read an integer from keyboard with
> DataInputStream can someone explain the behaviour
> of the following code ????
>
> <code>
> DataInputStream dis=new DataInputStream(System.in);
> DataOutputStream dout = new DataOutputStream(System.out);
> a=dis.readInt();
> System.out.println("Using system.out a = "+a);
> dout.writeInt(a);
> a++;
> System.out.println("Using system.out a = "+a);
> dout.writeInt(a);
> dout.flush();
> </code>
>
> the output is as under when 56 was entered as input
> <output>
> Using system.out a = 892734730
> 56
> Using system.out a = 892734731
> 56
>
> </output>
>
> isnt it logical that if readInt reads an integer (56) ,
> variable a should store 56 & not some other value ....
> what format does the DataInput reads in ?
>

It is designed to read in a value which is encoded as a binary integer. The
values from 'System.in' are *not* so-encoded, therefore you get what appear
to be random or nonsense values.

The data from 'System.in' is, instead, encoded as characters. When
performing interactive console I/O you will find that input is merely a
series of characters terminated by the newline character. Given this, the
usual method for performing such I/O is something like:

    BufferedReader br =
      new BufferedReader(
         new InputStreamReader(System.in));

    String input;

    while ((input = br.readLine()) != null)
    {
       ...
       System.out.println("Input Line: " + input);
       ...
       int i;

       try
       {
          i = Integer.parseInt(input);
         System.out.println("Converted integer value: " + i);
       }
       catch (NumberFormatException e)
      {
         // error ...
      }
       ...
    }

>
> coz when DataOutput is used the 56 appears corectly also
> the character ' ' where did it come from :O ?
>
> how do you store value in an int variable using
> DataInputStream or is it not meant for that ;) ?
>

It's actually meant to decode data that was originally written using a
'DataOutputStream' ! Although the results look strange, it is behaving
*exactly* as it should. The problem, as mentioned earlier, is that the wrong
type of data has been supplied to 'readInt'.

>
> i understand that stream stores it in different format that
> System.out does not understand but if we use the variable
> 'a' in some computation (of course we will otherwise why
> will you want to read it ;) )then the whole computation
> will go wrong what am i missing ?
>

It's a problem that traps many Java novices - live and learn :) !

I hope this helps.

Anthony Borla