简体   繁体   English

获取Java InputStream后面文件的字节数

[英]Get the number of bytes of a file behind a Java InputStream

As the title says, I need to know how many bytes the file has that's "behind" an InputStream. 如标题所示,我需要知道在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) 所以,我需要一个countBytes(InputStream inputStream)的实现。

Other than by consuming the entire stream and counting the bytes, you can't (there's no API for it). 除了消耗整个流并计算字节数之外,您不能(没有API)。

There's the available() method, but it quite explicitly doesn't do what you're asking: available()方法,但是很明显它并没有满足您的要求:

Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not . 请注意,虽然InputStream的某些实现将返回流中的字节总数,但许多实现则不会

If the InputStream is associated with a file (and not, say, a socket), perhaps you could use a different API to get its size? 如果InputStream与文件(而不是套接字)相关联,也许您可​​以使用其他API来获取文件的大小?

Could you leverage skip() in some way to approximate the size of the file? 您能以某种方式利用skip()来近似文件的大小吗?

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. 我也确信您可以使此循环更智能并避免不可避免的IOException ,但这是读者的一项练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM