File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes reading integers using Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "reading integers using" Watch "reading integers using" New topic

reading integers using

swapnil dey

Joined: Sep 25, 2000
Posts: 18
Hi all
so far ive used following code for reading integers from std i/p
DataInputStream ds= new DataInputStream(;
int i= Integer.parseInt(ds.readLine());
can i not use 'readInt()' of DataInputStream to read integers from std i/p. if yes how, if no why
int i= ds.readInt() gives a weird value... any explainations
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
hi dey!
when we accept input from keyboard it will be always string only.
we cannot accept integer values directly.when u read the input (even if the input is integers), that will be treated as when u said "ds.readInt()" , it is returning the unicode value of the integers u are accepting from keyboard.
i hope i could answer your question.
Serge Plourde
Ranch Hand

Joined: Jun 23, 2000
Posts: 140
Hi, Swapnil
bkkumar is right.
In the API, for DataInputStream, you can read:
readLine() Deprecated. This method does not properly convert
bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:
DataInputStream d = new DataInputStream(in);
BufferedReader d = new BufferedReader(new InputStreamReader(in));
In addition to this, the DataInputStream is not compatible with the BufferedReader.
So, in order to read the whole "line" of input, use the BufferedReader, as suggested.
Here is "one" of the many way of writing the code:
Serge Plourde
Ranch Hand

Joined: Jun 23, 2000
Posts: 140
I forgot to tell you, DataInputStream is really meant to handle data generated by DataOutPutStream. That's why you can't directly use readInt().
swapnil dey

Joined: Sep 25, 2000
Posts: 18
hi guys
thanx for helping, point taken
now i have few more related problems
say i create a form, n i wanna store the data in a binary file using DataOutputStream. when i try reading info from the file (using DataInputStream) there are no problems if the data is numeric,
but while reading text fields i get a warning coz readLine is deprecated ( as pointed out by bkkumar ), readBytes would require me to provide the number of bytes to be read,
i can't use Reader classes out there coz the result would be a text file which i don't want
is there any way out...
I agree. Here's the link:
subject: reading integers using
It's not a secret anymore!