0

I have the following method:

private long stream(final InputStream input, final OutputStream output) throws IOException {
    try (ReadableByteChannel inputChannel = Channels.newChannel(input); WritableByteChannel outputChannel = Channels.newChannel(output)) {
         final ByteBuffer buffer = ByteBuffer.allocate(10240);
         long size = 0;

         while (inputChannel.read(buffer) != -1) {
             buffer.flip();
             size += outputChannel.write(buffer);
             buffer.clear();
         }
         return size;
  }
}

There is a similar question:Question which says that it is due to jdk version. My main question is ByteBuffer.flip() calls the Buffer.flip() method then why am I getting java.lang.NoSuchMethodError? And why does the return type matters here when it is actually not used?

Shouldn't buffer.flip() and ((Buffer)buffer).flip() do the same thing?

  • Your `while (inputChannel.read(buffer) != -1)` should be `while (inputChannel.read(buffer) != -1) || buffer.position() > 0`, and your `buffer.clear()` should be `buffer.compact()`. Otherwise you are liable to the consequences of short writes. But why you're detouring through NIO when you have `java.io` streams is a mystery. There is no advantage. Just a lot more code to be executed. – user207421 Aug 25 '21 at 08:38

0 Answers0