Search code examples
javatestingfile-ioionio

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().


Solution

  • 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.