溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java中怎么加速讀取復(fù)制超大文件

發(fā)布時(shí)間:2021-06-11 15:42:10 來源:億速云 閱讀:156 作者:Leah 欄目:編程語言

今天就跟大家聊聊有關(guān)Java中怎么加速讀取復(fù)制超大文件,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

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("文件通道用時(shí):" + (end - start) + "毫秒");

start = System.currentTimeMillis();
copy(source, target);
end = System.currentTimeMillis();
System.out.println("普通緩沖用時(shí):" + (end - start) + "毫秒");
}

/**
  * 使用文件通道的方式復(fù)制文件
  * @param source 源文件
  * @param target 目標(biāo)文件
  */
 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();//得到對應(yīng)的文件通道
   outChannel = out.getChannel();//得到對應(yīng)的文件通道
   inChannel.transferTo(0, inChannel.size(), outChannel);//連接兩個(gè)通道,并且從inChannel通道讀取,然后寫入outChannel通道
  } catch (IOException e) {
    e.printStackTrace();
   } finally {
    try {
     in.close();
     inChannel.close();
     out.close();
     outChannel.close();
    } catch (IOException e) {
     e.printStackTrace();
    }


   }


  }
 
/**
* 普通緩沖復(fù)制
* @param source 源文件
* @param target 目標(biāo)文件
*/
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();
}
}
}
 }

 }

看完上述內(nèi)容,你們對Java中怎么加速讀取復(fù)制超大文件有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI