使用FileChannel复制文件

论坛 期权论坛 脚本     
已经匿名di用户   2022-5-29 19:26   2637   0

方法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) {

}
}
}
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP