Dos, base nio de programación Java (buffers directos y no directos buffer)

I. Antecedentes

1. Llevar a cabo blog anterior, continuamos a estudiar bajo la programación nio hoy, preámbulos, comenzó a resumir la actualidad. Específico puede consultar el artículo: https://blog.csdn.net/chenmingxu438521/article/details/103967066

En segundo lugar, la distinción entre directos e indirectos tamponada con tampón

tampones 1. no directos: () para asignar un búfer por asignar, a partir de la memoria intermedia en la JVM

 2. Buffer directa: () método de asignación de memorias intermedias de modo directo allocateDirect, la memoria intermedia se establece en la memoria física. Puede mejorar la eficiencia

3. Analizar

3.1. Búfer de bytes es directa o no directa. Si el buffer de bytes directa, la máquina virtual de Java hacer todo lo posible para llevar a cabo las operaciones de E / S nativas directamente en este buffer. Es decir, antes de cada llamada al sistema operativo subyacente, un I / nativos de operaciones de E (o posterior), la máquina virtual tratará de evitar copiar el contenido de la memoria intermedia de la memoria intermedia intermedia (o copiar el contenido del buffer intermedio ).

3,2 representa el canal abierto al dispositivo IO (por ejemplo archivos .:, socket) conexiones. sistema NIO si se requiere, necesita obtener un canal para conectar el dispositivo y los medios IO tampón para la recepción de datos. Buffer A continuación, se hace funcionar, el procesamiento de datos. Canal es responsable del transporte, tampón responsable del almacenamiento. Paso definido por paquete java.nio.channels. Canal representa la conexión de origen y de destino IO abierta. Canal similar a la tradicional "flujo". Canalizarse pero no puede acceder directamente a los datos, el canal sólo se puede interactuar con Tampón.

4. Código

@Test
	// 使用直接缓冲区完成文件的复制(內存映射文件)
	public void test2() throws IOException {
		FileChannel inChannel = FileChannel.open(Paths.get("1.png"), StandardOpenOption.READ);
		FileChannel outChannel = FileChannel.open(Paths.get("2.png"), StandardOpenOption.READ, StandardOpenOption.WRITE,
				StandardOpenOption.CREATE);
		// 映射文件
		MappedByteBuffer inMapperBuff = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
		MappedByteBuffer outMapperBuff = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
		// 直接对缓冲区进行数据读写操作
		byte[] dst = new byte[inMapperBuff.limit()];
		inMapperBuff.get(dst);
		outMapperBuff.put(dst);
		outChannel.close();
		inChannel.close();
	}

	@Test
	// 1.利用通道完成文件复制(非直接缓冲区)
	public void test1() throws IOException {
		FileInputStream fis = new FileInputStream("1.png");
		FileOutputStream fos = new FileOutputStream("2.png");
		// ①获取到通道
		FileChannel inChannel = fis.getChannel();
		FileChannel outChannel = fos.getChannel();

		// ②分配指定大小的缓冲区
		ByteBuffer buf = ByteBuffer.allocate(1024);
		while (inChannel.read(buf) != -1) {
			buf.flip();// 切换到读取模式
			outChannel.write(buf);
			buf.clear();// 清空缓冲区
		}
		// 关闭连接
		outChannel.close();
		inChannel.close();
		fos.close();
		fis.close();
	}
直接缓冲区与非直接缓冲耗时计算
	@Test
	// 使用直接缓冲区完成文件的复制(內存映射文件) //428、357
	public void test2() throws IOException {
		long startTime = System.currentTimeMillis();
		FileChannel inChannel = FileChannel.open(Paths.get("f://1.mp4"), StandardOpenOption.READ);
		FileChannel outChannel = FileChannel.open(Paths.get("f://2.mp4"), StandardOpenOption.READ, StandardOpenOption.WRITE,
				StandardOpenOption.CREATE);
		// 映射文件
		MappedByteBuffer inMapperBuff = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
		MappedByteBuffer outMapperBuff = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
		// 直接对缓冲区进行数据读写操作
		byte[] dst = new byte[inMapperBuff.limit()];
		inMapperBuff.get(dst);
		outMapperBuff.put(dst);
		outChannel.close();
		inChannel.close();
		long endTime = System.currentTimeMillis();
		System.out.println("内存映射文件耗时:"+(endTime-startTime));
	}
	@Test
	// 1.利用通道完成文件复制(非直接缓冲区)
	public void test1() throws IOException {  //11953 、3207、3337
		long startTime = System.currentTimeMillis();
		FileInputStream fis = new FileInputStream("f://1.mp4");
		FileOutputStream fos = new FileOutputStream("f://2.mp4");
		// ①获取到通道
		FileChannel inChannel = fis.getChannel();
		FileChannel outChannel = fos.getChannel();

		// ②分配指定大小的缓冲区
		ByteBuffer buf = ByteBuffer.allocate(1024);
		while (inChannel.read(buf) != -1) {
			buf.flip();// 切换到读取模式
			outChannel.write(buf);
			buf.clear();// 清空缓冲区
		}
		// 关闭连接
		outChannel.close();
		inChannel.close();
		fos.close();
		fis.close();
		long endTime = System.currentTimeMillis();
		System.out.println("非缓冲区:"+(endTime-startTime));
	}

En tercer lugar, la dispersión agregada lectura y escritura

1. dispersión leer (Lee El Scattering) : dispersión de una pluralidad de tampón de canal de datos

2. escritura agregación (escribe The Gathering) : la agregación de una pluralidad de memorias intermedias de datos en el paso

3. Código

public class Test004 {
    public static void main(String[] args) throws IOException {
        RandomAccessFile raf1 = new RandomAccessFile("e://test.txt", "rw");
        // 1.获取通道
        FileChannel channel = raf1.getChannel();
        // 2.分配指定大小的指定缓冲区
        ByteBuffer buf1 = ByteBuffer.allocate(100);
        ByteBuffer buf2 = ByteBuffer.allocate(1024);
        // 3.分散读取
        ByteBuffer[] bufs = { buf1, buf2 };
        channel.read(bufs);
        for (ByteBuffer byteBuffer : bufs) {
            // 切换为读取模式
            byteBuffer.flip();
        }
        System.out.println(new String(bufs[0].array(), 0, bufs[0].limit()));
        System.out.println("------------------分算读取线分割--------------------");
        System.out.println(new String(bufs[1].array(), 0, bufs[1].limit()));
        // 聚集写入
        RandomAccessFile raf2 = new RandomAccessFile("e://2.txt", "rw");
        FileChannel channel2 = raf2.getChannel();
        channel2.write(bufs);
    }
}

En cuarto lugar, el fin de la

¡¡¡Siempre mantén la fe!!!

Publicados 122 artículos originales · ganado elogios 64 · Vistas a 50000 +

Supongo que te gusta

Origin blog.csdn.net/chenmingxu438521/article/details/103968684
Recomendado
Clasificación