I've been trying to do communication from another language to Java, but when I try read data from DataInputStream in a while loop...
static String getData(DataInputStream stream){
int charbyte;
StringBuilder strbuilder = new StringBuilder();
try {
while ((charbyte = stream.read()) != -1){
strbuilder.append(Character.toChars(charbyte));
}
stream.close();
return new String(strbuilder);
} catch (Exception e) {
return null;
}
}
The problem is stream.read() is not returning -1 because it just keeps waiting for new data to be sent. How can I just get the data that was just sent?
The method never returns because the while loop never ends, and this is caused by the connection or the DataInputStream remaining open.
To send a variable number of bytes over a network connection where the reader reads a stream of characters you have three options:
For #1, change the loop to
try {
int count = stream.readInt();
for( int i = 0; i < count; ++i ){
strbuilder.append(Character.toChars(stream.read()));
}
return strbuilder.toString();
}
For #2, use
try {
while ((charbyte = stream.read()) != 0){
strbuilder.append(Character.toChars(charbyte));
}
return strbuilder.toString();
}
The code you have now is for #3.