NIO读写文件例子

该博客演示了Java中使用RandomAccessFile、FileChannel和MappedByteBuffer进行文件读写、内存映射以及数据传输的实现。内容包括分散读取、聚集写入、直接缓冲区的便捷使用以及内存映射文件的操作。通过这些技术,可以高效地处理大文件并提高I/O性能。
摘要由CSDN通过智能技术生成
/**
	 * 分散读取与聚集写入
	 * @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();
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值