Java IO流之通道与内存映射

版权声明:LemonSnm https://blog.csdn.net/LemonSnm/article/details/90045686

通道:

通道读写文件示例:

内存映射读写文件示例:

package com.lemon;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

/**
 *IO操作的性能比较:
 * 1.内存映射最快
 * 2.NIO读写文件
 * 3.使用缓存的IO流
 * 4.无缓存的IO流
 *
 * @author lemonSun
 * 2019年5月9日下午8:36:39
 */
public class CopyFileDemo {

	public static void main(String[] args) throws Exception  {
		
		//copyFile();
		RandoramAccessFileDemo();
	}
	/**
	 * 内存映射:
	 * 实现文件复制
	 * @throws Exception
	 */
	private static void RandoramAccessFileDemo() throws Exception {
		
		RandomAccessFile in = new RandomAccessFile("F:\\javatest\\123.mp4","r");
		RandomAccessFile out = new RandomAccessFile("F:\\javatest\\text1\\123.mp4","rw");
		//添加通道:
		FileChannel fcIn = in.getChannel();
		FileChannel fcOut = out.getChannel();
		
		
		long size = fcIn.size(); //输入流的字节大小
		//两个通道映射到缓冲区
		MappedByteBuffer inBuf = fcIn.map(MapMode.READ_ONLY, 0, size);//输入流映射 只读
		MappedByteBuffer outBuf = fcOut.map(MapMode.READ_WRITE,0,size);//输出流映射 可读可写
		
		//一读一写
		for (int i = 0; i < size; i++) {
			outBuf.put(inBuf.get());
		}
		//关闭(关闭通道时,数据写入)
		fcIn.close();
		fcOut.close();
		in.close();
		out.close();
		System.out.println("copy success!");
	}
	
	/**
	 * FileChannel: 文件通道
	 * 通过文件通道,实现文件的复制
	 * @throws Exception
	 */
	private static void copyFile() throws Exception{
		
		//创建一个文件输入文件的通道
				FileChannel fcIn = new FileInputStream("F:\\javatest\\233.jpg").getChannel();
				//管道输出文件的通道
				FileChannel fcOut = new FileOutputStream("F:\\javatest\\text1\\233.jpg").getChannel();
				
				//创建一个1024字节的缓冲区
				ByteBuffer buf = ByteBuffer.allocate(1024);
				while(fcIn.read(buf) != -1) {
					buf.flip(); //缓存区可能没装满 反转下
					fcOut.write(buf);  //反转后满了,就不用0,len了
					buf.clear(); //清空缓冲区
				}
				fcIn.close();
				fcOut.close();
				System.out.println("copy success!");
	}
	
}

猜你喜欢

转载自blog.csdn.net/LemonSnm/article/details/90045686
今日推荐