nio 分散读取与聚集写入实现文件的复制

package com.atguigu.nio;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.junit.Test;

public class TestNio {

	@Test
	public void test() throws IOException {
		RandomAccessFile ranf = new RandomAccessFile("C:/Users/Administrator/Desktop/1.jpg", "r");
		FileChannel channel = ranf.getChannel();
		// 多个buffer
		ByteBuffer buff1 = ByteBuffer.allocate(10001);
		ByteBuffer buff2 = ByteBuffer.allocate(10001);

		ByteBuffer buff3 = ByteBuffer.allocate(10001);
       //将buff放在数组中
		ByteBuffer[] bus = new ByteBuffer[] { buff1, buff2, buff3 };
		//channel进行文件读取
		long read = channel.read(bus);
		for (ByteBuffer byteBuffer : bus) {
			byteBuffer.flip();
		}
		RandomAccessFile ran2 = new RandomAccessFile("C:/Users/Administrator/Desktop/12.jpg", "rw");
		//channel实现文件写入
		FileChannel channel2 = ran2.getChannel();
		channel2.write(bus);

	}
}
发布了17 篇原创文章 · 获赞 3 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_36547601/article/details/81506841