---
title: "java之nio（3）"
author: "747017186"
date: "2018-12-24T09:48:54Z"
tags: []
categories: ["编程语言"]
slug: "java-nio-3"
draft: false
lastmod: "2018-12-23T21:02:48Z"
id: 2435567
url: "https://747017186.iteye.com/blog/2435567"
---

**通道(Channel)**  
**![](http://dl2.iteye.com/upload/attachment/0131/2624/120f6761-58d6-3f8e-8fa8-94b97778dc76.png)**  
**![](http://dl2.iteye.com/upload/attachment/0131/2626/5ea05fe3-1525-33cc-8243-648d82a909d9.png)**  
 **channel边读边写**

```
package nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ChannelTest {
	public static void main(String[] args) throws Exception{
		ByteBuffer buffer = ByteBuffer.allocate(10);//开辟10个缓冲区
		
		//读文件
		FileInputStream in = new FileInputStream("F:\\1.txt");
		FileChannel inChannel = in.getChannel();
		
		//写文件
		FileOutputStream out = new FileOutputStream("F:\\2.txt");
		FileChannel outChannel = out.getChannel();
		
		String str = "12345";//初始化信息
		buffer.put(str.getBytes());//把初始化信息放入缓冲区
		int temp = 0;
		while((temp=inChannel.read(buffer))!=-1) {//如果还有多余的缓冲区则继续读取直到缓冲区满
			buffer.flip();//每次缓冲区重置（通过改变position=0），必须把内容展示出来
			outChannel.write(buffer);//写入通道
			buffer.clear();//每次必须清空缓冲区，否则while循环每次 read读取的时候的缓冲区已满，read不会再读取新内容，陷入死循环
		}
		inChannel.close();
		in.close();
		outChannel.close();
		out.close();
	}
	
	private static void printInfo(ByteBuffer buffer) {
		while(buffer.hasRemaining()) {
			System.out.print((char)buffer.get()+"、");
		}
		System.out.println();
	}
}
```

**MappedByteBuffer（内存映射流）**

**![](http://dl2.iteye.com/upload/attachment/0131/2628/190a6592-2156-3ea6-b9e7-b23e4a5cf28f.png)**  
**![](http://dl2.iteye.com/upload/attachment/0131/2630/9bd9a69f-de16-3b98-adf3-960e3f9996e9.png)**  
**![](http://dl2.iteye.com/upload/attachment/0131/2632/7a14d51d-2e16-3f9b-896d-cd48d6c3e96a.png)**  
 **代码：**

```
package nio;

import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class MappedByteBufferTest {
	public static void main(String[] args) throws Exception{
		//读文件
		FileInputStream in = new FileInputStream("F:\\1.txt");
		FileChannel inChannel = in.getChannel();
		
		//开辟内存通道，只读模式，大小为文件大小,MappedByteBuffer只为MapMode.READ_ONLY，如果要操作写模式太危险
		MappedByteBuffer mappedByteBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, in.available());
		printInfo(mappedByteBuffer);
		
		inChannel.close();
		in.close();
	}
	
	private static void printInfo(ByteBuffer buffer) {
		while(buffer.hasRemaining()) {
			System.out.print((char)buffer.get()+"、");
		}
		System.out.println();
	}
}
```