我正在学习 java nio,我正在使用 MappedByteBuffer 和 ExecutorService 异步复制文件。我的问题是 MappedByteBuffer.put() 方法抛出 java.nio.BufferOverflowException。但在我的调试中,我没有复制到目标文件的上方位置。这是我用来创建文件的新副本的代码部分:
for (Future<?> f : futures) {
Message message = (Message) f.get();
try (FileChannel fileChannel = (FileChannel) Files
.newByteChannel(pathWrite, EnumSet.of(
StandardOpenOption.READ,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING))) {
MappedByteBuffer mbb = fileChannel.map(
FileChannel.MapMode.READ_WRITE, message.getCod(),
message.getValue());
if (mbb != null) {
System.out.println("start: " + message.getCod()
+ " - end: " + message.getValue());
ByteBuffer encode = Charset.forName(charEncoding)
.encode(message.getCharBuffer());
mbb.put(encode); // here
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
例外是:
java.nio.BufferOverflowException
at java.nio.DirectByteBuffer.put(DirectByteBuffer.java:363)
at java.nio.DirectByteBuffer.put(DirectByteBuffer.java:342)
at memo.MultiThreadingMappedByteBufferExample.multiThreadedWayWithExecutorService(MultiThreadingMappedByteBufferExample.java:139)