利用FileChannel复制文件
来源:互联网 发布:古墓丽影崛起帧数优化 编辑:程序博客网 时间:2024/05/01 00:34
方法1:
public static void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
//从inChannel文件中读出count bytes ,并写入outChannel文件。
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
也可以这么写:
public static void copyFile(File src, File dst) throws IOException {
private static final int BSIZE = 1024;
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
//从inChannel文件中读出count bytes ,并写入outChannel文件。
ByteBuffer bb = ByteBuffer.allocate(BSIZE);
while(in.read(bb)!=-1){
bb.flip();
out.write(bb);
bb.clear();//prepare for reading;清空缓冲区;
}
} finally {
也可以这么写: