What's wrong with my use of DataInputStream.readUTF() ??

R

rhimbo

Hi folks,

I'm writing a simple program to prompt the user at the console and read
the line of data items entered. The data will consist of
space-separated items of type int and String like this:

1233 "some text" "more text"

I want to read a line of data at a time and then extract the elements
with the DataInputStream methods readInt(), readUTF(), etc.

My program seems to hang waiting on the DataInputStream.readUTF() call.
I can call every other DataInputStream method just fine, such as
readInt(), readLong(), etc.

Actually, when I change the program to read one item at a time I get
the same behavior. I can read everything fine except the strings. The
readUTF() call hangs.

Here is the basic loop of the program.


...
int uid = 0;
boolean online = false;
String username = null;
String email = null;
String message = null;


public void run()
{
DataInput dataInput = new DataInputStream(System.in);

while (true)
{
System.out.println("Enter record to insert in database...");
System.out.println("<uid> <username> <email> <online ?> <msg>...");
System.out.print("? ");

try
{
uid = dataInput.readInt();
username = dataInput.readUTF();
email = dataInput.readUTF();
online = dataInput.readBoolean();
message = dataInput.readUTF();
}
catch (EOFException eof)
{
// Reached end of input.
System.out.println(eof.getMessage());
break;
}
catch (UTFDataFormatException dfe)
{
System.out.println(dfe.getMessage());
break;
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
break;
}

outputData(output);
}
}
 
C

Chris Uppal

rhimbo said:
1233 "some text" "more text"

I want to read a line of data at a time and then extract the elements
with the DataInputStream methods readInt(), readUTF(), etc.

DataInputStream is the wrong tool for this job -- it reads a /binary/
representation of integers (etc) from the underlying binary stream.

You should wrap a java.io.InputStreamReader around System.in, and go from
there.

-- chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top