java高效實(shí)現(xiàn)大文件拷貝功能
在java中,F(xiàn)ileChannel類中有一些優(yōu)化方法可以提高傳輸?shù)男剩渲衪ransferTo( )和 transferFrom( )方法允許將一個(gè)通道交叉連接到另一個(gè)通道,而不需要通過一個(gè)緩沖區(qū)來傳遞數(shù)據(jù)。只有FileChannel類有這兩個(gè)方法,因此 channel-to-channel 傳輸中通道之一必須是 FileChannel。不能在sock通道之間傳輸數(shù)據(jù),不過socket 通道實(shí)現(xiàn)WritableByteChannel 和 ReadableByteChannel 接口,因此文件的內(nèi)容可以用 transferTo( )方法傳輸給一個(gè) socket 通道,或者也可以用 transferFrom( )方法將數(shù)據(jù)從一個(gè) socket 通道直接讀取到一個(gè)文件中。
Channel-to-channel 傳輸是可以極其快速的,特別是在底層操作系統(tǒng)提供本地支持的時(shí)候。某些操作系統(tǒng)可以不必通過用戶空間傳遞數(shù)據(jù)而進(jìn)行直接的數(shù)據(jù)傳輸。對(duì)于大量的數(shù)據(jù)傳輸,這會(huì)是一個(gè)巨大的幫助。
注意:如果要拷貝的文件大于4G,則不能直接用Channel-to-channel 的方法,替代的方法是使用ByteBuffer,先從原文件通道讀取到ByteBuffer,再將ByteBuffer寫到目標(biāo)文件通道中。
下面為實(shí)現(xiàn)大文件快速拷貝的代碼:
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class BigFileCopy {
/**
* 通過channel到channel直接傳輸
* @param source
* @param dest
* @throws IOException
*/
public static void copyByChannelToChannel(String source, String dest) throws IOException {
File source_tmp_file = new File(source);
if (!source_tmp_file.exists()) {
return ;
}
RandomAccessFile source_file = new RandomAccessFile(source_tmp_file, "r");
FileChannel source_channel = source_file.getChannel();
File dest_tmp_file = new File(dest);
if (!dest_tmp_file.isFile()) {
if (!dest_tmp_file.createNewFile()) {
source_channel.close();
source_file.close();
return;
}
}
RandomAccessFile dest_file = new RandomAccessFile(dest_tmp_file, "rw");
FileChannel dest_channel = dest_file.getChannel();
long left_size = source_channel.size();
long position = 0;
while (left_size > 0) {
long write_size = source_channel.transferTo(position, left_size, dest_channel);
position += write_size;
left_size -= write_size;
}
source_channel.close();
source_file.close();
dest_channel.close();
dest_file.close();
}
public static void main(String[] args) {
try {
long start_time = System.currentTimeMillis();
BigFileCopy.copyByChannelToChannel("source_file", "dest_file");
long end_time = System.currentTimeMillis();
System.out.println("copy time = " + (end_time - start_time));
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot集成Druid數(shù)據(jù)庫(kù)連接池
這篇文章主要介紹了Spring Boot集成Druid數(shù)據(jù)庫(kù)連接池,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-04-04
Java實(shí)現(xiàn)的百度語音識(shí)別功能示例
這篇文章主要介紹了Java實(shí)現(xiàn)的百度語音識(shí)別功能,較為簡(jiǎn)明扼要的分析了Java調(diào)用百度語音接口相關(guān)操作步驟,并給出了具體的語音識(shí)別用法代碼示例,需要的朋友可以參考下2018-08-08
Java編程中的構(gòu)造函數(shù)詳細(xì)介紹
這篇文章主要介紹了Java編程中的構(gòu)造函數(shù)詳細(xì)介紹,介紹了其概念,格式,與其他函數(shù)的區(qū)別,作用等相關(guān)內(nèi)容,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11
Java final static abstract關(guān)鍵字概述
這篇文章主要介紹了Java final static abstract關(guān)鍵字的相關(guān)資料,需要的朋友可以參考下2016-05-05

