Java文件復(fù)制的高效方法——文件通道
在Java編程中,復(fù)制文件是一項(xiàng)常見(jiàn)的任務(wù)。我們通常使用緩沖輸入輸出流來(lái)實(shí)現(xiàn)文件復(fù)制操作,然而,在研究JDK文檔時(shí),我們可以發(fā)現(xiàn)使用文件通道(FileChannel)來(lái)實(shí)現(xiàn)文件復(fù)制竟然比傳統(tǒng)的方式快了
在Java編程中,復(fù)制文件是一項(xiàng)常見(jiàn)的任務(wù)。我們通常使用緩沖輸入輸出流來(lái)實(shí)現(xiàn)文件復(fù)制操作,然而,在研究JDK文檔時(shí),我們可以發(fā)現(xiàn)使用文件通道(FileChannel)來(lái)實(shí)現(xiàn)文件復(fù)制竟然比傳統(tǒng)的方式快了近三分之一。
使用文件通道的方式復(fù)制文件
下面我們來(lái)介紹如何使用文件通道來(lái)實(shí)現(xiàn)文件復(fù)制:
```java
public void fileChannelCopy(File s, File t) {
FileInputStream fi null;
FileOutputStream fo null;
FileChannel in null;
FileChannel out null;
try {
fi new FileInputStream(s);
fo new FileOutputStream(t);
in ();//得到對(duì)應(yīng)的文件通道
out ();//得到對(duì)應(yīng)的文件通道
(0, (), out);//連接兩個(gè)通道,并且從in通道讀取,然后寫(xiě)入out通道
} catch (IOException e) {
();
} finally {
try {
();
();
();
();
} catch (IOException e) {
();
}
}
}
```
與普通的緩沖輸入輸出流的復(fù)制效率的對(duì)比
接下來(lái),我們來(lái)測(cè)試一下使用文件通道和緩沖輸入輸出流的復(fù)制效率并進(jìn)行對(duì)比:
普通的緩沖輸入輸出流代碼:
```java
public void bufferedStreamCopy(File s, File t) {
BufferedInputStream bis null;
BufferedOutputStream bos null;
try {
bis new BufferedInputStream(new FileInputStream(s));
bos new BufferedOutputStream(new FileOutputStream(t));
byte[] buf new byte[1024];
int len;
while ((len (buf)) ! -1) {
bos.write(buf, 0, len);
}
} catch (IOException e) {
();
} finally {
try {
();
();
} catch (IOException e) {
();
}
}
}
```
測(cè)試代碼:
```java
long start ();
fileChannelCopy(source, target);
long end ();
("使用文件通道復(fù)制文件,耗時(shí):" (end - start) "ms");
start ();
bufferedStreamCopy(source, target2);
end ();
("使用緩沖輸入輸出流復(fù)制文件,耗時(shí):" (end - start) "ms");
```
輸出結(jié)果:
使用文件通道復(fù)制文件,耗時(shí):9ms
使用緩沖輸入輸出流復(fù)制文件,耗時(shí):13ms
由此可見(jiàn),使用文件通道復(fù)制文件的速度比使用緩沖輸入輸出流快了將近三分之一,在復(fù)制大文件時(shí),更加體現(xiàn)出其速度優(yōu)勢(shì)。而且,F(xiàn)ileChannel也是多并發(fā)線程安全的。
結(jié)語(yǔ)
以上就是FileChannel復(fù)制文件的高效方法,相信在實(shí)際工作中會(huì)有所幫助。同時(shí),本文作者也是一名普通的Java開(kāi)發(fā)者,如有錯(cuò)誤之處,請(qǐng)多多指教。