nio的拷贝文件大概能比io拷贝文件快1倍左右,为何会快1倍了,查看了它的源码,发现它用到了直接内存,即与jvm内存相比,省去了一次拷贝。所以能加快速度,但它也是一把双刃剑,有如下缺点,可以不借用cpu,是独立的处理器,专门用于处理io
①,申请内存空间比较慢
②,直接内存不属于jvm管理范围内,释放比较难,可能会造成oom问题,出现问题比较难排查
import java.io.*;
import java.nio.channels.FileChannel;
/**
* @author hui
* @date 2019/6/12
*/
public class IOUtil {
public static void fileCopyWithFileChannel( FileInputStream fileInputStream,FileOutputStream fileOutputStream) {
FileChannel fileChannelInput = null;
FileChannel fileChannelOutput = null;
try {
// 得到fileInputStream的文件通道
fileChannelInput = fileInputStream.getChannel();
// 得到fileOutputStream的文件通道
fileChannelOutput = fileOutputStream.getChannel();
// 将fileChannelInput通道的数据,写入到fileChannelOutput通道
fileChannelInput.transferTo(0, fileChannelInput.size(), fileChannelOutput);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 用filechannel进行文件复制
*
* @param fromFile
* 源文件
* @param toFile
* 目标文件
*/
public static void fileCopyWithFileChannel(File fromFile, File toFile) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream=new FileInputStream(fromFile);
fileOutputStream=new FileOutputStream(toFile);
fileCopyWithFileChannel(fileInputStream, fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
IOUtil.close(fileOutputStream);
IOUtil.close(fileInputStream);
}
}
public static long copy(final InputStream input, final OutputStream output)
throws IOException {
byte[] buffer = new byte[1024];
long count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
public static void close(Closeable closeable){
if(closeable != null){
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
普通的流的拷贝