Java NIO 获取channel的三种方式 对象调用getChannel 方法 通过FileChannel.open方式 通过FileChannel.open方式 分散Scatter和聚集Gather 字符集 编码 解码
通道Channel
用于连接源节点和目标节点;
在 Java NIO 中负责缓冲区中数据的传输;
Channel 本身不存储数据,因此需要配合缓冲区进行传输。
java.nio.channels.Channel 接口的主要实现类
- FileChannel:用于读取、写入、映射和操作文件的通道。
- DatagramChannel:通过 UDP 读写网络中的数据通道。
- SocketChannel:通过 TCP 读写网络中的数据。
- ServerSocketChannel:可以监听新进来的 TCP 连接,对每一个新进来的连接都会创建一个 SocketChannel。
获取通道的三种方法
1、支持通道的对象调用getChannel() 方法。
支持通道的类如下:
- FileInputStream
- FileOutputStream
- RandomAccessFile
- DatagramSocket
- Socket
- ServerSocket
2、Files 工具类的静态方法 newByteChannel() 获取字节通道
3、通过通道的静态方法 open() 打开并返回指定通道。
FileChannel 的常用方法
方 法 | 描 述 |
---|---|
int read(ByteBuffer dst) | 从 Channel 中读取数据到 ByteBuffer |
long read(ByteBuffer[] dsts) | 将 Channel 中的数据“分散”到 ByteBuffer[] |
int write(ByteBuffer src) | 将 ByteBuffer 中的数据写入到 Channel |
long write(ByteBuffer[] srcs) | 将 ByteBuffer[] 中的数据“聚集”到 Channel |
long position() | 返回此通道的文件位置 |
FileChannel position(long p) | 设置此通道的文件位置 |
long size() | 返回此通道的文件的当前大小 |
FileChannel truncate(long s) | 将此通道的文件截取为给定大小 |
void force(boolean metaData) | 强制将所有对此通道的文件更新写入到存储设备中 |
获取通道方法一 :对象调用getChannel() 方法
示例1:
/**
* 通过通道完成文件复制
*/
private static void copyFileByGetChannel() {
long startTime = System.currentTimeMillis();
FileInputStream is = null;
FileOutputStream os = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
is = new FileInputStream("D:/Sunxy_workspace/nio_resource/fireworks.jpg");
os = new FileOutputStream("D:/Sunxy_workspace/nio_resource/fireworksChannel.jpg");
// 对象调用getChannel()方法 获取通道
inChannel = is.getChannel();
outChannel = os.getChannel();
//因为通道不能传输数据,需要使用缓冲区传输数据;创建指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
// 将通道中的数据存入缓冲区中
while (inChannel.read(buf) != -1) {
buf.flip(); // 读写模式切换,读模式切换成写模式
outChannel.write(buf); // 将缓冲区的数据写入通道中
buf.clear(); // 清空缓冲区
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outChannel != null) {
try {
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inChannel != null) {
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
long endTime = System.currentTimeMillis();
System.out.println("getChannel方式 复制文件耗时:" + (endTime - startTime) + "毫秒");
}
获取通道方法二 :通过FileChannel.open() 方式
示例1:
/**
* 使用直接缓冲区完成文件的复制(内存映射文件)
* 通过FileChannel.open() 方式复制文件
*/
private static void copyFileByFileChannelOpenToDirect() throws Exception{
long startTime = System.currentTimeMillis();
// 获取一个通道,赋予该通道读取权限
FileChannel inChannel = FileChannel.open(Paths.get("D:/Sunxy_workspace/nio_resource/fireworks.jpg"), StandardOpenOption.READ);
// 获取一个通道,赋予该通道写入,创建文件的权限
FileChannel outChannel = FileChannel.open(Paths.get("D:/Sunxy_workspace/nio_resource/fireworksOpenChannel.jpg"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
// 内存映射文件 (创建直接缓冲区)
MappedByteBuffer inMapBuf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outMapBuf = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());
//直接对缓冲区进行数据的读写操作
byte[] dst = new byte[inMapBuf.limit()];
inMapBuf.get(dst); // 从inMapBuf获取数据到dst
outMapBuf.put(dst); // 把dst放到outMapBuf中
inChannel.close();
outChannel.close();
long endTime = System.currentTimeMillis();
System.out.println("FileChannel.open方式(直接缓冲区) 复制文件耗时:" + (endTime - startTime) + "毫秒");
}
示例2:
/**
* 通道之间的数据传输(直接缓冲区)
* A transferTo B :将A通道的数据输出到B通道
* B transferFrom A :B通道的数据来自A通道,或者B通道用来接收A通道的数据
**/
private static void copyFileByFileChannelOpenTransferToDirect() throws IOException {
// 获取一个通道,赋予该通道读取权限
FileChannel inChannel = FileChannel.open(Paths.get("D:/Sunxy_workspace/nio_resource/fireworks.jpg"), StandardOpenOption.READ);
// 获取一个通道,赋予该通道写入,创建文件的权限
FileChannel outChannel = FileChannel.open(Paths.get("D:/Sunxy_workspace/nio_resource/fireworksOpenChannelTransfer.jpg"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
// 将inChannel通道的数据输出到outChannel通道
//inChannel.transferTo(0,inChannel.size(),outChannel);
// B通道的数据来自A通道
outChannel.transferFrom(inChannel,0,inChannel.size());
inChannel.close();
outChannel.close();
}
注意:直接缓冲区:虽然能够提升复制文件的速度;存在磁盘文件已经复制完成,java程序却不能及时完成,需要等待gc回收开辟的物理内存对象后,程序才能完成。
获取通道方法三 :通过Files.newByteChannel方式
示例1:
/**
* 通过Files.newByteChannel方式 复制文件
**/
private static void copyFileByFilesNewByteChannel() throws IOException {
SeekableByteChannel inSeekChannel = Files.newByteChannel(Paths.get("D:/Sunxy_workspace/nio_resource/fireworks.jpg"), StandardOpenOption.READ);
SeekableByteChannel outSeekChannel = Files.newByteChannel(Paths.get("D:/Sunxy_workspace/nio_resource/fireworksNewByteChannel.jpg"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);
ByteBuffer buf = ByteBuffer.allocate(1024);
while (inSeekChannel.read(buf) != -1) {
buf.flip();
outSeekChannel.write(buf);
buf.clear();
}
inSeekChannel.close();
outSeekChannel.close();
}
分散(Scatter)和聚集(Gather)
分散读取(Scattering Reads)是指从 Channel 中读取的数据“分散”到多个 Buffer 中。
按照缓冲区的顺序,从 Channel 中读取的数据依次将 Buffer 填满
聚集写入(Gathering Writes)是指将多个 Buffer 中的数据“聚集”到 Channel
按照缓冲区的顺序,写入 position 和 limit 之间的数据到 Channel
示:1:
/**
* 分散(Scatter)读取文件
* 聚集(Gather)写入文件
**/
private static void ScatterGather() throws IOException {
RandomAccessFile inFile = new RandomAccessFile("D:/Sunxy_workspace/nio_resource/Scatter.txt", "rw");
//1. 获取通道
FileChannel inChannel = inFile.getChannel();
//2. 分配指定大小的缓冲区
ByteBuffer buf1 = ByteBuffer.allocate(100);
ByteBuffer buf2 = ByteBuffer.allocate(1024);
//3. 分散读取
ByteBuffer[] buffers = {buf1, buf2};
inChannel.read(buffers);
// 读写反转
for (ByteBuffer byteBuffer : buffers) {
byteBuffer.flip();
}
System.out.println(new String(buffers[0].array(), 0, buffers[0].limit()));
System.out.println("----------------------------------");
System.out.println(new String(buffers[1].array(), 0, buffers[1].limit()));
//4. 聚集写入
RandomAccessFile outFile = new RandomAccessFile("D:/Sunxy_workspace/nio_resource/Gather.txt", "rw");
FileChannel outChannel = outFile.getChannel();
outChannel.write(buffers);
}
字符集 编码 解码
示例1
/**
* 字符集 编码 解码
**/
private static void charsetEncoderDecoder() throws CharacterCodingException {
Charset charset = Charset.forName("GBK");
//获取编码器
CharsetEncoder encoder = charset.newEncoder();
CharBuffer charBuffer = CharBuffer.allocate(1024);
charBuffer.put("五星红旗迎风飘");
charBuffer.flip();
//编码 将charBuffer中的内容编码成Byte
ByteBuffer byteBuffer = encoder.encode(charBuffer);
for (int i = 0; i < byteBuffer.limit(); i++) {
System.out.println(byteBuffer.get());
}
//转换为写模式
byteBuffer.flip();
//获取解码器
CharsetDecoder decoder = charset.newDecoder();
//解码
CharBuffer charBuff = decoder.decode(byteBuffer);
System.out.println(charBuff.toString());
System.out.println("----------------------------------");
// 直接解码
Charset charsetGBK = Charset.forName("GBK");
byteBuffer.flip();
CharBuffer cBuf3 = charsetGBK.decode(byteBuffer);
System.out.println(cBuf3.toString());
}
完整示例如下
package com.nio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
/**
* 获取channel的三种方式
* 分散(Scatter)和聚集(Gather)
* 字符集 编码 解码
*/
public class NioChannel {
public static void main(String[] args) throws Exception {
copyFileByGetChannel();
copyFileByFileChannelOpenToDirect();
copyFileByFileChannelOpenTransferToDirect();
copyFileByFilesNewByteChannel();
ScatterGather();
charsetEncoderDecoder();
}
/**
* 字符集 编码 解码
**/
private static void charsetEncoderDecoder() throws CharacterCodingException {
Charset charset = Charset.forName("GBK");
//获取编码器
CharsetEncoder encoder = charset.newEncoder();
CharBuffer charBuffer = CharBuffer.allocate(1024);
charBuffer.put("五星红旗迎风飘");
charBuffer.flip();
//编码 将charBuffer中的内容编码成Byte
ByteBuffer byteBuffer = encoder.encode(charBuffer);
for (int i = 0; i < byteBuffer.limit(); i++) {
System.out.println(byteBuffer.get());
}
//转换为写模式
byteBuffer.flip();
//获取解码器
CharsetDecoder decoder = charset.newDecoder();
//解码
CharBuffer charBuff = decoder.decode(byteBuffer);
System.out.println(charBuff.toString());
System.out.println("----------------------------------");
// 直接解码
Charset charsetGBK = Charset.forName("GBK");
byteBuffer.flip();
CharBuffer cBuf3 = charsetGBK.decode(byteBuffer);
System.out.println(cBuf3.toString());
}
/**
* 分散(Scatter)读取文件
* 聚集(Gather)写入文件
**/
private static void ScatterGather() throws IOException {
RandomAccessFile inFile = new RandomAccessFile("D:/Sunxy_workspace/nio_resource/Scatter.txt", "rw");
//1. 获取通道
FileChannel inChannel = inFile.getChannel();
//2. 分配指定大小的缓冲区
ByteBuffer buf1 = ByteBuffer.allocate(100);
ByteBuffer buf2 = ByteBuffer.allocate(1024);
//3. 分散读取
ByteBuffer[] buffers = {buf1, buf2};
inChannel.read(buffers);
// 读写反转
for (ByteBuffer byteBuffer : buffers) {
byteBuffer.flip();
}
System.out.println(new String(buffers[0].array(), 0, buffers[0].limit()));
System.out.println("----------------------------------");
System.out.println(new String(buffers[1].array(), 0, buffers[1].limit()));
//4. 聚集写入
RandomAccessFile outFile = new RandomAccessFile("D:/Sunxy_workspace/nio_resource/Gather.txt", "rw");
FileChannel outChannel = outFile.getChannel();
outChannel.write(buffers);
}
/**
* 通过Files.newByteChannel方式 复制文件
**/
private static void copyFileByFilesNewByteChannel() throws IOException {
SeekableByteChannel inSeekChannel = Files.newByteChannel(Paths.get("D:/Sunxy_workspace/nio_resource/fireworks.jpg"), StandardOpenOption.READ);
SeekableByteChannel outSeekChannel = Files.newByteChannel(Paths.get("D:/Sunxy_workspace/nio_resource/fireworksNewByteChannel.jpg"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);
ByteBuffer buf = ByteBuffer.allocate(1024);
while (inSeekChannel.read(buf) != -1) {
buf.flip();
outSeekChannel.write(buf);
buf.clear();
}
inSeekChannel.close();
outSeekChannel.close();
}
/**
* 通道之间的数据传输(直接缓冲区)
* A transferTo B :将A通道的数据输出到B通道
* B transferFrom A :B通道的数据来自A通道,或者B通道用来接收A通道的数据
**/
private static void copyFileByFileChannelOpenTransferToDirect() throws IOException {
// 获取一个通道,赋予该通道读取权限
FileChannel inChannel = FileChannel.open(Paths.get("D:/Sunxy_workspace/nio_resource/fireworks.jpg"), StandardOpenOption.READ);
// 获取一个通道,赋予该通道写入,创建文件的权限
FileChannel outChannel = FileChannel.open(Paths.get("D:/Sunxy_workspace/nio_resource/fireworksOpenChannelTransfer.jpg"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
// 将inChannel通道的数据输出到outChannel通道
//inChannel.transferTo(0,inChannel.size(),outChannel);
// B通道的数据来自A通道
outChannel.transferFrom(inChannel,0,inChannel.size());
inChannel.close();
outChannel.close();
}
/**
* 使用直接缓冲区完成文件的复制(内存映射文件)
* 通过FileChannel.open() 方式复制文件
*/
private static void copyFileByFileChannelOpenToDirect() throws Exception{
long startTime = System.currentTimeMillis();
// 获取一个通道,赋予该通道读取权限
FileChannel inChannel = FileChannel.open(Paths.get("D:/Sunxy_workspace/nio_resource/fireworks.jpg"), StandardOpenOption.READ);
// 获取一个通道,赋予该通道写入,创建文件的权限
FileChannel outChannel = FileChannel.open(Paths.get("D:/Sunxy_workspace/nio_resource/fireworksOpenChannel.jpg"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
// 内存映射文件 (创建直接缓冲区)
MappedByteBuffer inMapBuf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outMapBuf = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());
//直接对缓冲区进行数据的读写操作
byte[] dst = new byte[inMapBuf.limit()];
inMapBuf.get(dst); // 从inMapBuf获取数据到dst
outMapBuf.put(dst); // 把dst放到outMapBuf中
inChannel.close();
outChannel.close();
long endTime = System.currentTimeMillis();
System.out.println("FileChannel.open方式(直接缓冲区) 复制文件耗时:" + (endTime - startTime) + "毫秒");
}
/**
* 通过通道完成文件复制
*/
private static void copyFileByGetChannel() {
long startTime = System.currentTimeMillis();
FileInputStream is = null;
FileOutputStream os = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
is = new FileInputStream("D:/Sunxy_workspace/nio_resource/fireworks.jpg");
os = new FileOutputStream("D:/Sunxy_workspace/nio_resource/fireworksChannel.jpg");
// 对象调用getChannel()方法 获取通道
inChannel = is.getChannel();
outChannel = os.getChannel();
//因为通道不能传输数据,需要使用缓冲区传输数据;创建指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
// 将通道中的数据存入缓冲区中
while (inChannel.read(buf) != -1) {
buf.flip(); // 读写模式切换,读模式切换成写模式
outChannel.write(buf); // 将缓冲区的数据写入通道中
buf.clear(); // 清空缓冲区
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outChannel != null) {
try {
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inChannel != null) {
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
long endTime = System.currentTimeMillis();
System.out.println("getChannel方式 复制文件耗时:" + (endTime - startTime) + "毫秒");
}
}
代码仓库:https://gitee.com/lingyiwin/Learn_Java