Check if DataInputStream has content
Asked Answered
T

3

5

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?

Tanny answered 19/1, 2014 at 12:2 Comment(0)
V
5
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

Vassaux answered 19/1, 2014 at 12:7 Comment(3)
then try to read and then unread data from it.If it really doesnt return anything.Then its empty and available(); works like it shoudVassaux
If you click that link you shoud get pretty good idea how to do it in loop,Also there is answer that explain why it returns 0 in some case,check documentation for dis as well.Vassaux
Ok now using a PushBackInputStream and the dis, pbs for the available, dis for rest ;)Tanny
S
3

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()

Straightjacket answered 19/1, 2014 at 12:8 Comment(0)
C
0

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);
    }
Commonable answered 20/9, 2019 at 14:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.