Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: create a bytearray-backed FileChannel

I have a class for IO that uses ByteBuffer to buffer access to a FileChannel (so it basically accepts a FileChannel at the constructor). I'd like to unittest it, so it'd be nice if I could get a bytearray-backed FileChannel to avoid creating and deleting files during test.

To get you an idea, it'd be perfect if I could get something like ByteArrayOutputStream.getChannel().

like image 573
marcorossi Avatar asked Oct 29 '11 17:10

marcorossi


1 Answers

You can use Channels.newChannel(InputStream) or Channels.newChannel(OutputStream) but those will give you a ReadableByteChannel or a WritableByteChannel. They won't give you a FileChannel, which makes sense given that you don't have a file - a FileChannel without a file doesn't make any sense. If you change your class to accept any ReadableByteChannel or WritableByteChannel, that should be fine.

like image 78
Jon Skeet Avatar answered Sep 24 '22 18:09

Jon Skeet