</pre><pre name="code" class="java">package com.jack.io.bio;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class FileTest {
private BufferedOutputStream bos;
private BufferedInputStream bis;
private FileInputStream fis;
private FileOutputStream fos;
private FileChannel fin;
private FileChannel fout;
//传统方式 速度慢,效率差,容易出错
public void copyFile(String srcPath, String tgtPath) {
try {
bis = new BufferedInputStream(new FileInputStream(srcPath));
bos = new BufferedOutputStream(new FileOutputStream(tgtPath));
int len;
byte[] buffer = new byte[1024 * 1024];
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//速度快 ,效率高,零拷贝
//http://www.ibm.com/developerworks/cn/java/j-zerocopy/
public void copyFile2(String srcPath, String tgtPath) {
long length;
try {
fis = new FileInputStream(srcPath);
fin = fis.getChannel();
fos = new FileOutputStream(tgtPath);
fout = fos.getChannel();
length = fin.size();
fin.transferTo(0, length, fout);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fin != null) {
try {
fin.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fout != null) {
try {
fout.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//Try-with-resource jdk1.7新特性
//效率高,简短,不容易出错
public void copyFileJdk17(String srcPath, String tgtPath) {
try(FileInputStream fis2 = new FileInputStream(srcPath);
FileChannel fin2 = fis2.getChannel();
FileOutputStream fos2 = new FileOutputStream(tgtPath);
FileChannel fout2 = fos2.getChannel()){
fin2.transferTo(0, fin2.size(), fout2);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
FileTest test = new FileTest();
test.copyFileJdk17("e:\\test.mp4", "e:\\test2.mp4");
}
}
java 文件复制
最新推荐文章于 2023-03-26 23:17:57 发布