Seeking a ByteArrayInputStream using java.io

后端 未结 3 1600
误落风尘
误落风尘 2021-01-04 10:43

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 a

相关标签:
3条回答
  • 2021-01-04 11:34

    There is a ByteArrayInputStream(byte(), int, int) constructor that will give you an input stream that will read up to a given count of bytes starting from a given offset. You can use this to simulate seeking to an arbitrary offset in the stream.

    You have to deal with the fact that "seeking" gives you a new stream object, and this may be awkward. However, this approach does not involve copying any bytes or saving them to a file, and it should be safe to not bother with closing the ByteArrayInputStream objects.

    0 讨论(0)
  • 2021-01-04 11:44

    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);
    }
    

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

    0 讨论(0)
  • 2021-01-04 11:46

    If you are creating the ByteArrayInputStream to pass elsewhere, extend the class and manipulate pos (a protected member of ByteArrayInputStream) as you wish.

    0 讨论(0)
提交回复
热议问题