您的位置:首页 > 其它

使用FileChannel复制文件

2009-11-02 12:40 246 查看
方法1:

public void copyFile(File src, File dest) {
FileChannel in = null;
FileChannel out = null;
try {
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest);
in = fis.getChannel();
out = fos.getChannel();

ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE);
while (true) {
int size = in.read(buf);
if (size == -1) {
break;
}
buf.flip();
out.write(buf);
}

} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) try {in.close();} catch(Exception e) {}
if (out != null) try {out.close();} catch(Exception e) {}
}
}

方法2:

public void copyFile2(File src, File dest) {
FileChannel sfc = null;
FileChannel dfc = null;
try {
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest);
sfc = fis.getChannel();
dfc = fos.getChannel();

sfc.transferTo(0, sfc.size(), dfc);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sfc != null) {
try {
sfc.close();
} catch (IOException e) {
}
}
if (dfc != null) {
try {
dfc.close();
} catch (Exception e) {

}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: