Java InputStream大小 [英] Java InputStream size

查看:287
本文介绍了Java InputStream大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在不创建File实例的情况下获取InputStream的大小(以字节为单位).有什么办法可以使用Java NIO做到这一点?

I need to get the size in bytes of an InputStream without creating a File instance. Is there any way to do it using Java NIO?

推荐答案

一般InputStream的?您只需要继续读和读(例如,一次又一次地读入同一缓冲区),就可以算出已读的字节数,直到到达流的末尾为止.

Of a general InputStream? You'd have to just keep reading and reading (e.g. into the same buffer, over and over) counting how many bytes you've read, until you come to the end of the stream.

当然,您将无法读取数据本身...如果要执行此操作,则需要在读取数据时保留数据,例如通过将其复制到ByteArrayOutputStream.

Of course, you then won't be able to read the data itself... if you want to do that, you'll need to keep the data as you read it, e.g. by copying it to a ByteArrayOutputStream.

(如果您能够在计算长度的同时处理数据,请执行此操作-在使用循环读取数据时,每次读入相同的缓冲区时,只需增加一个计数器来记录如何您已经阅读了很多书.您还没有真正为我们提供有关您要对信息流进行处理的任何信息.)

(If you're able to process the data at the same time as working out the length, just do that - as you read it using a loop, reading into the same buffer each time, just increment a counter to record how much you've read. You haven't really provided us any information about what you want to do with the stream.)

这篇关于Java InputStream大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆