/**
* 分散读取与聚集写入
* @throws Exception
*/
@Test
public void test4() throws Exception {
RandomAccessFile file = new RandomAccessFile("D:\\2.txt", "rw");
FileChannel channel1 = file.getChannel();
ByteBuffer buff1 = ByteBuffer.allocate(20);
ByteBuffer buff2 = ByteBuffer.allocate(120);
ByteBuffer[] dsts= {buff1,buff2};
channel1.read(dsts);
for (ByteBuffer byteBuffer : dsts) {
byteBuffer.flip();
}
System.out.println(new String(dsts[0].array(),0,dsts[0].limit()));
System.out.println("---------------------------------------------");
System.out.println(new String(dsts[1].array(),0,dsts[1].limit()));
RandomAccessFile file2 = new RandomAccessFile("D:\\test4.txt", "rw");
FileChannel channel2 = file2.getChannel();
channel2.write(dsts);
}
/**
* 更方便的使用直接缓冲区
* @throws Exception
*/
@Test
public void test3() throws Exception {
FileChannel inChannel = FileChannel.open(Paths.get("D:\\1.png"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("D:\\transfer2.png"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
//inChannel.transferTo(0, inChannel.size(), outChannel);
outChannel.transferFrom(inChannel, 0, inChannel.size());
outChannel.close();
inChannel.close();
}
/**
* 使用channel直接操作内存
* @throws Exception
*/
@Test
public void test2() throws Exception {
FileChannel inChannel = FileChannel.open(Paths.get("D:\\1.png"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("D:\\test2.png"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
//内存映射文件
MappedByteBuffer inbuffer = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outbuffer = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
byte[] bt = new byte[inbuffer.limit()];
inbuffer.get(bt);
outbuffer.put(bt);
inChannel.close();
outChannel.close();
}
@Test
public void test1() throws Exception {
FileInputStream ins = new FileInputStream("D:\\1.png");
FileOutputStream outs = new FileOutputStream("D:\\2.png");
FileChannel inChannel = ins.getChannel();
FileChannel outChannel = outs.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(inChannel.read(buffer)!=-1) { //read读是读到buffer中
buffer.flip();
outChannel.write(buffer); //write写是从buffer中写出来
buffer.clear();
}
outChannel.close();
inChannel.close();
outs.close();
ins.close();
}