Get the number of bytes of a file behind a Java InputStream

ε祈祈猫儿з 提交于 2019-12-23 19:14:13

问题


As the title says, I need to know how many bytes the file has that's "behind" an InputStream. I don't want to download all bytes and count (takes to long). I just need to know how many bytes the file has.

Like this:

int numberOfBytes = countBytes(inputStream);

So, I need an implementation for countBytes(InputStream inputStream)


回答1:


Other than by consuming the entire stream and counting the bytes, you can't (there's no API for it).

There's the available() method, but it quite explicitly doesn't do what you're asking:

Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not.

If the InputStream is associated with a file (and not, say, a socket), perhaps you could use a different API to get its size?




回答2:


Could you leverage skip() in some way to approximate the size of the file?

int bytes = 1024; // Chunk size for skipping. Adjust as necessary
try {
    int skipped = 0;
    while(stream.available()) {
        stream.skip(bytes);
        skipped += bytes;
        // Elided...do something with skipped
    }
} catch(IOException ex) {
    // Handle a skip that's too big
}

I'm sure too that you could make this loop smarter and avoid the inevitable IOException, but that's an exercise left to the reader.



来源:https://stackoverflow.com/questions/8505670/get-the-number-of-bytes-of-a-file-behind-a-java-inputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!