给定一个 Java InputStream,我如何确定流中的当前偏移量?
我想要一个通用的、可重用的 getPosition() 方法,它可以告诉我从流的起始点读取的字节数。 理想情况下,我希望它能够与所有输入流一起使用,这样当我从不同的来源获取它们时,我就不必包装它们中的每一个。
这样的野兽存在吗? 如果没有,任何人都可以推荐计数InputStream
的现有实现吗?
I'd like something like a generic, re-usable getPosition()
method that will tell me the number of bytes read from the starting point of the stream. Ideally, I would prefer this to work with all InputStreams, so that I don't have to wrap each and every one of them as I get them from disparate sources.
Does such a beast exist? If not, can anyone recommend an existing implementation of a counting InputStream
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要遵循
java.io
中建立的装饰器模式来实现这一点。让我们在这里尝试一下:
InputStreams 旨在是线程安全的,因此可以考虑同步的自由使用。 我尝试了
volatile
和AtomicLong
位置变量,但同步可能是最好的,因为它允许一个线程在流上操作并查询其位置而不放弃锁定。You'll need to follow the Decorator pattern established in
java.io
to implement this.Let's give it a try here:
The InputStreams are intended to be thread safe, so that accounts for the liberal use of synchronization. I played around with
volatile
andAtomicLong
position variables, but synchronization is probably best because it allows one thread to operate on the stream and query its position without relinquishing the lock.查看 CountingInputStream 中的公共 IO 包。 他们还收集了很多其他有用的 InputStream 变体。
Take a look at CountingInputStream in the Commons IO package. They have a pretty good collection of other useful InputStream variants as well.
Guava 中还有
CountingInputStream
。API文档:
https://google.github .io/guava/releases/19.0/api/docs/com/google/common/io/CountingInputStream.html
来源:https://github.com/google/guava/blob/master/guava/src/com/google/common/io /CountingInputStream.java
There is also
CountingInputStream
in Guava.Apidocs:
https://google.github.io/guava/releases/19.0/api/docs/com/google/common/io/CountingInputStream.html
Source: https://github.com/google/guava/blob/master/guava/src/com/google/common/io/CountingInputStream.java
不。
InputStream
旨在处理潜在的无限量数据,因此计数器会成为障碍。 除了将它们全部包装起来之外,您还可以对方面做一些事情。No.
InputStream
is intended to handle potentially infinite amounts of data, so a counter would get in the way. In addition to wrapping them all, you might be able to do something with aspects.