通道
用于源节点与目标节点的连接,在java NIO中负责缓冲区中数据传输,Channel本身不存储数据,因此需要配合缓冲区进行传输
通道的主要实现类
java.nio.channel.Channel接口:
FileChannel
SocketChannel
ServerSocketChannel
DatagramChannel
获取通道
1.java针对通道类提供了getChannel()方法
本地IO:
FileInputStream/FileOutputStream
RandomAccessFile
网络IO:
Socket
ServerSocket
DatagramSocket
2.JDK1.7中NIO.2针对各个通道提供了静态方法open() Files工具类的newByteChannel()
代码实现利用通道完成文件的复制(非直接缓冲区)
@Test
//1.利用通道完成文件的复制(非直接缓冲区)
public void test1() {
long start = System.currentTimeMillis();
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
//①获取通道
fis = new FileInputStream("a.txt");
fos = new FileOutputStream("copya.txt");
inChannel = fis.getChannel();
outChannel = fos.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 (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
long end = System.currentTimeMillis();
System.out.println("耗费的时间为 : "+ (end - start));
}
//耗费的时间为 : 50
使用直接缓冲区完成文件的复制(内存映射文件)
//使用直接缓冲区完成文件的复制
@Test
public void test2() throws IOException {
long start = System.currentTimeMillis();
FileChannel inChannel = FileChannel.open(Paths.get("a.txt"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("copy2a.txt"), StandardOpenOption.WRITE,StandardOpenOption.READ
,StandardOpenOption.CREATE);
//内存映射文件
MappedByteBuffer inMappedBuf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outMapperBuf = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());
//直接对缓冲区进行数据的读写操作
byte[] dst = new byte[inMappedBuf.limit()];
inMappedBuf.get(dst);
outMapperBuf.put(dst);
inChannel.close();
outChannel.close();
long end = System.currentTimeMillis();
System.out.println("耗费的时间为 : "+(end - start));
}
//耗费的时间为 : 75
/*
直接字节缓冲区可以通过此类的allocateDirect()工厂方法来创建,此方法返回的缓冲区进行分配和取消
分配所需成本通常高于非直接缓冲区,直接缓冲区的内容可以驻留在常规的垃圾回收堆之外,因此它们对应用程序的
内存需求量造成的影响可能并不明显,所以,建议将直接缓冲区主要分配给那些易受基础系统的本机I/O操作影响的大型
持久的缓冲区,一般情况下.最好只在直接缓冲区能在程序性能方面带来明显好处时分配它们
*/
通道之间的数据传输(直接缓冲区)
@Test
public void test3() throws IOException {
FileChannel inChannel = FileChannel.open(Paths.get("a.txt"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("copy3a.txt"), StandardOpenOption.WRITE,StandardOpenOption.READ
,StandardOpenOption.CREATE);
inChannel.transferTo(0,inChannel.size(),outChannel);
outChannel.transferFrom(inChannel,0,inChannel.size());
outChannel.close();
inChannel.close();
}
















