使用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) {
}
}
}
}
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) {
}
}
}
}
相关文章推荐
- 使用FileChannel(文件通道)来实现文件快速复制
- 使用FileChannel实现文件复制
- VS调试出现错误提示 无法将“obj\Debug\*.*”复制到“bin\Debug\*.*”,文件正在由另一个进程使用,因此该进程无法访问此文件
- 使用NIO与BIO复制文件性能对比
- 【我的Java笔记】IO流_使用IO流进行文件的复制和粘贴
- Java 使用字节流 一次性复制文件
- C#使用FileStream复制多媒体文件
- [懵懂边缘]使用C#在进度条中显示复制文件的进度
- 使用IO技术,创建一个目录,然后复制一个文件到该目录!实现复制的功能。(在博客园上传的第一份代码)
- hadoop文件复制的使用实例
- 使用字节流的方式实现文件的复制
- [并发并行]_[C/C++]_[使用线程本地存储Thread Local Storage(TLS)调用复制文件接口的案例]
- 使用paramiko模块复制远程文件到本地
- 使用API函数复制文件,可显示进度。
- 使用mmap即文件映射实现文件的快速复制
- .net 流——使用流进行文件复制
- Linux 使用expect工具和scp命令实现自动复制传输文件
- 多线程编程实例:不带缓冲的多线程文件复制 (使用pread pwrite版本)
- linux学习之路之使用脚本来复制二进制程序和所需的库文件
- 使用C#在进度条中显示复制文件的进度