您的位置 首页 java

Java,NIO,零拷贝是transferTo方法的实现

零拷贝

避免CPU将数据从一块存储拷贝到另外一块存储的技术。

针对操作系统中的设备驱动程序、文件系统以及网络协议堆栈而出现的各种零拷贝技术极大地提升了特定应用程序的性能,并且使得这些应用程序可以更加有效地利用系统资源。这种性能的提升就是通过在数据拷贝进行的同时,允许 CPU执行其他的任务来实现的。

零拷贝技术可以减少数据拷贝和共享总线操作的次数,消除传输数据在存储器之间不必要的中间拷贝次数,从而有效地提高数据传输效率。

JavaNIO零拷贝是transferTo方法实现

1、Java NIO的零拷贝由transferTo()方法实现;

2、transferTo()方法将数据从FileChannel对象传送到可写的字节通道(如:Socket Channel等);

3、transferTo()方法内部实现中,由native方法transferTo0()来实现,它依赖底层操作系统的支持;

4、在UNIX和Linux系统中,调用这个方法会引起sendfile()系统调用,实现了数据直接从内核的读缓冲区传输到套接字缓冲区,避免了用户态(User-space)与内核态(Kernel-space)之间的数据拷贝;

JavaNIO transferTo方法应用

功能:拷贝多少数据到目标通道;

long transferTo(long position, long count, WritableByteChannel target) throws IOException;

1、position,起始位置;

2、count,读取长度;

3、target,目标通道

4、返回值:实际传输的字节数,可能为零;

JavaNIO transferFrom方法应用

功能:从源通道中拷贝多少数据到目标通道;

long transferFrom(ReadableByteChannel src,long position, long count) throws IOException;

1、src,原始通道;

2、position,起始位置;

3、count,读取长度;

4、返回值:实际传输的字节数,可能为零;

案例代码:

 import java.io.File;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.StandardOpenOption;

public class NioChannelControllerDemo {

public static void main(String[] args) {
String readFilePath = "F:\\MySoftware\\06\\aaaa.exe";
String writeFilePath = "e:/aaaa.exe";
long timeStar = System.currentTimeMillis();
copy2(new File(readFilePath),new File(writeFilePath));
long timeEnd = System.currentTimeMillis();
System.out.println("Copy time :" + (timeEnd - timeStar) + "ms");
// Copy time :473ms
}

public static void copy(File src, File dst) {
try (
FileChannel in = FileChannel.open(src.toPath(), StandardOpenOption.READ);
FileChannel out = FileChannel.open(dst.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE)
) {
in.transferTo(0, in.size(), out);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

/**
 * @param src
 * @param dst
 */public static void copy2(File src, File dst) {
try (
FileChannel in = FileChannel.open(src.toPath(), StandardOpenOption.READ);
FileChannel out = FileChannel.open(dst.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE)
) {
out.transferFrom(in, 0, in.size());
} catch (IOException e) {
throw new RuntimeException(e);
}
}

}  

文章来源:智云一二三科技

文章标题:Java,NIO,零拷贝是transferTo方法的实现

文章地址:https://www.zhihuclub.com/181784.shtml

关于作者: 智云科技

热门文章

发表回复

您的电子邮箱地址不会被公开。

网站地图