分散读取,聚集写入
package com.cppdy.nio; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; //分散读取,聚集写入 public class NIOBufferDemo5 { public static void main(String[] args) throws Exception { RandomAccessFile raf = new RandomAccessFile("F:\cppdy\1.txt", "rw"); FileChannel channel = raf.getChannel(); ByteBuffer buf1 = ByteBuffer.allocate(100); ByteBuffer buf2 = ByteBuffer.allocate(1024); ByteBuffer[] bufs = { buf1, buf2 }; channel.read(bufs); for (int i = 0; i < bufs.length; i++) { ByteBuffer byteBuffer = bufs[i]; byteBuffer.flip(); } System.out.println("buf1:" + new String(bufs[0].array(), 0, bufs[0].limit())); System.out.println("-----------------------------------------------------"); System.out.println("buf2:" + new String(bufs[1].array(), 0, bufs[1].limit())); RandomAccessFile raf2 = new RandomAccessFile("F:\cppdy\2.txt", "rw"); FileChannel channel2 = raf2.getChannel(); channel2.write(bufs); channel.close(); channel2.close(); } }