现在有网络传输文件的需求,需要先将文件写出到服务器本地磁盘(需求见:https://blog.csdn.net/u014532775/article/details/101306634),采用传统的IO流速度较慢,在这做一个总结,不同场景和文件大小可以使用不同的方式。
1.传统的IO读取方式:
/**
* 最传统的方式 40M文件 byte字节1024时平均220ms byte字节8192时平均时长70ms
* @throws Exception
*/
public static void traditionTest() throws Exception{
FileInputStream inputStream = new FileInputStream(new File("\\home\\www\\source.mp4"));
FileOutputStream outputStream = new FileOutputStream(new File("\\home\\www\\target.mp4"));
byte[] bytes = new byte[1024];
int len;
while ((len = inputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
outputStream.close();
inputStream.close();
}
2.使用java8或者commons IO的FileUtils或者guava包下的copy方法:
/**
* 使用java8或者commons IO的FileUtils或者guava包下的copy方法 40M文件 80ms左右
* @throws Exception
*/
public static void fileUtilTest() throws Exception{
FileInputStream inputStream = new FileInputStream(new File("\\home\\www\\source.mp4"));
File out = new File("\\home\\www\\target.mp4");
Files.copy(inputStream,out.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
3.FileChannel方式:
/**
* FileChannel方式 这种是综合效率最高的一种读写方式 40M文件 60ms左右 用到了nio相关知识
*/
public static void nioTest() throws Exception{
FileInputStream inputStream = new FileInputStream(new File("\\home\\www\\source.mp4"));
FileOutputStream outputStream = new FileOutputStream(new File("\\home\\www\\target.mp4"));
FileChannel in = inputStream.getChannel();
FileChannel out = outputStream.getChannel();
in.transferTo(0,in.size(),out);
}
推荐采用FileChannel方式,传输速度较高
如果输入的是InputStream,处理方式可以参考:https://www.cnblogs.com/asfeixue/p/9065681.html