使用java.io寻找ByteArrayInputStream [英] Seeking a ByteArrayInputStream using java.io

查看:123
本文介绍了使用java.io寻找ByteArrayInputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何寻找(更改位置) ByteArrayInputStream java.io )?它是如此明显的东西,但我似乎无法在任何地方找到一个方法(标记 / 重置是还不够,我需要将位置设置为 InputStream 上的任何位置。

How can I seek (change the position) of a ByteArrayInputStream (java.io)? It is something so obvious, but I can't seem to find a method for this anywhere (mark/reset is not enough, I need to set the position to anywhere on the InputStream).

如果不能使用 java.io 完成,我必须切换到 java.nio 并使用 ByteBuffer ,如何使用<$ c $获得类似 DataOutputStream 包装 ByteArrayOutputStream 的内容C> java.nio中?我没有找到任何类型的可自动调整大小的缓冲区。

If it can't be done using java.io and I must switch to java.nio and use a ByteBuffer, how can I get something similar to a DataOutputStream wrapping a ByteArrayOutputStream using java.nio? I'm not finding any kind of auto-resizable buffer.

编辑:我找到了一种方法来实现我正在尝试的要做,但有点凌乱。 ImageIO.createImageInputStream 创建一个 ImageInputStream ,这正是我想要的(可以搜索和读取基元)。但是,使用 ByteArrayInputStream 会返回 FileCacheImageInputStream ,这基本上意味着它将字节数组复制到一个文件中以进行搜索。

I've found one way to achieve what I'm attempting to do, but it's a bit messy. ImageIO.createImageInputStream creates a ImageInputStream, which is exactly what I want (can seek and read primitives). However, using a ByteArrayInputStream returns a FileCacheImageInputStream, which basically means it copies the byte array to a file just to seek.

这是我第一次尝试使用Java IO类,但它完全是否定的。它缺少一些基本的(IMO)功能,它有很多方法可以做同样的事情(例如,从文件中读取原语,你可以使用 RandomAccessFile DataInputStream + FileInputStream FileImageInputStream FileChannel + ByteBuffer ,甚至更多)。

This is my first time trying to use the Java IO classes and it has been completely negative. It's missing some fundamental (IMO) features, and it has lots of ways to do the same thing (e.g. to read primitives from a file you can either use RandomAccessFile, DataInputStream + FileInputStream, FileImageInputStream, FileChannel + ByteBuffer, and maybe even more).

推荐答案

您使用 reset() / skip()。我不能说它是世界上最好的API,但它应该可以工作:

You'd use reset()/skip(). I can't say it's the nicest API in the world, but it should work:

public void seek(ByteArrayInputStream input, int position)
    throws IOException
{
    input.reset();
    input.skip(position);
}

当然,假设没有人打电话给 mark()

Of course, that assumes that no-one has called mark().

这篇关于使用java.io寻找ByteArrayInputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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