Java中怎么加速读取复制超大文件

发布时间:2021-06-11 15:42:10 作者:Leah
来源:亿速云 阅读:137

今天就跟大家聊聊有关Java中怎么加速读取复制超大文件,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

package test;
 import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.nio.channels.FileChannel;

 public class Test {
public static void main(String[] args) {
File source = new File("E:\\tools\\fmw_12.1.3.0.0_wls.jar");
File target = new File("E:\\tools\\fmw_12.1.3.0.0_wls-copy.jar");
long start, end;

start = System.currentTimeMillis();
fileChannelCopy(source, target);
end = System.currentTimeMillis();
System.out.println("文件通道用时:" + (end - start) + "毫秒");

start = System.currentTimeMillis();
copy(source, target);
end = System.currentTimeMillis();
System.out.println("普通缓冲用时:" + (end - start) + "毫秒");
}

/**
  * 使用文件通道的方式复制文件
  * @param source 源文件
  * @param target 目标文件
  */
 public static void fileChannelCopy(File source, File target) {


   FileInputStream in = null;
   FileOutputStream out = null;
   FileChannel inChannel = null;
   FileChannel outChannel = null;
   try {
    in = new FileInputStream(source);
    out = new FileOutputStream(target);
    inChannel = in.getChannel();//得到对应的文件通道
   outChannel = out.getChannel();//得到对应的文件通道
   inChannel.transferTo(0, inChannel.size(), outChannel);//连接两个通道,并且从inChannel通道读取,然后写入outChannel通道
  } catch (IOException e) {
    e.printStackTrace();
   } finally {
    try {
     in.close();
     inChannel.close();
     out.close();
     outChannel.close();
    } catch (IOException e) {
     e.printStackTrace();
    }


   }


  }
 
/**
* 普通缓冲复制
* @param source 源文件
* @param target 目标文件
*/
public static void copy (File source, File target) {
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(source));
out = new BufferedOutputStream(new FileOutputStream(target));
byte[] buf = new byte[4096];
int i;
while ((i = in.read(buf)) != -1) {
out.write(buf, 0, i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
 }

 }

看完上述内容,你们对Java中怎么加速读取复制超大文件有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. Python基于read(size)方法读取超大文件
  2. java使用多线程读取超大文件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:java怎么实现一个邮件通知工具类

下一篇:开启Spring Boot的方式有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》