新聞中心
1. 使用FileStreams復(fù)制
為崇義等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及崇義網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為做網(wǎng)站、網(wǎng)站制作、崇義網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!
這是最經(jīng)典的方式將一個(gè)文件的內(nèi)容復(fù)制到另一個(gè)文件中。 使用FileInputStream讀取文件A的字節(jié),使用FileOutputStream寫入到文件B。
這是第一個(gè)方法的代碼:
private static void copyFileUsingFileStreams(File source, File dest)
throws IOException {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(source);
output = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
} finally {
input.close();
output.close();
}
}
正如你所看到的我們執(zhí)行幾個(gè)讀和寫操作try的數(shù)據(jù),所以這應(yīng)該是一個(gè)低效率的,下一個(gè)方法我們將看到新的方式。
2. 使用FileChannel復(fù)制
Java NIO包括transferFrom方法,根據(jù)文檔應(yīng)該比文件流復(fù)制的速度更快。
這是第二種方法的代碼:
private static void copyFileUsingFileChannels(File source, File dest) throws IOException {
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
inputChannel.close();
outputChannel.close();
}
}

3. 使用Commons IO復(fù)制
Apache Commons IO提供拷貝文件方法在其FileUtils類,可用于復(fù)制一個(gè)文件到另一個(gè)地方。它非常方便使用Apache Commons FileUtils類時(shí),您已經(jīng)使用您的項(xiàng)目。
基本上,這個(gè)類使用Java NIO FileChannel內(nèi)部。
這是第三種方法的代碼:
private static void copyFileUsingApacheCommonsIO(File source, File dest)
throws IOException {
FileUtils.copyFile(source, dest);
}
4. 使用Java7的Files類復(fù)制
如果你有一些經(jīng)驗(yàn)在Java 7中你可能會(huì)知道,可以使用復(fù)制方法的Files類文件,從一個(gè)文件復(fù)制到另一個(gè)文件。
這是第四個(gè)方法的代碼:
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
詳情更多了解:http://shenzhen.offcn.com/
新聞名稱:java復(fù)制文件的4種方式
當(dāng)前路徑:http://www.dlmjj.cn/article/pddjcd.html