سؤال

Is there a way to ask a DataInputStream, if it has content to read? .readByte() will just hang it, waiting for a byte to be read :( Or do I always have to send a Dummy-Byte, to make sure it always sees something?

هل كانت مفيدة؟

المحلول

dis.available();

Returns: an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking.

Is this what you looking for?

also check answers here. You might get even more informations. "available" of DataInputStream from Socket

نصائح أخرى

Look at

 public int available() throws IOException

according to docs it "Returns an estimate of the number of bytes that can be read"

so you should call dis.available()

When reading past the end of the file, an EOFException is thrown. So you can tell there's no more data to read. For examle:

 DataInputStream inputStream = new DataInputStream(new FileInputStream(file));
    int data = 0;
    try {
        while (true) {
            data += inputStream.readInt();
        }
    } catch (EOFException e) {
        System.out.println("All data were read");
        System.out.println(data);
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top