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

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

问题描述

如何寻找(改变位置)ByteArrayInputStream (java.io)?这是如此明显的事情,但我似乎无法在任何地方找到这种方法(mark/reset 是不够的,我需要将位置设置为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,怎么办我得到了类似于 DataOutputStream 的东西,它使用 java.nio 包装了一个 ByteArrayOutputStream?我没有找到任何类型的可自动调整大小的缓冲区.

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) 功能,并且有很多方法可以做同样的事情(例如,从文件中读取原语,您可以使用 RandomAccessFileDataInputStream +FileInputStreamFileImageInputStreamFileChannel + 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天全站免登陆