package com.io.cx2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 文件拷贝:文件字节输入、输出流
*/
public class test5 {
public static void main(String[] args) {
copy("D:\\EclipsePlace\\IO\\src\\com\\io\\cx2\\test5.java","dest.txt");
//第一个是要拷贝的文件的地址,第二个是拷贝后的文件
}
/**
* 文件的拷贝
* 可以利用递归 制作文件夹的拷贝(mkdirs)
*/
public static void copy(String srcPath,String destPath) {
//1、创建源
File src = new File(srcPath); //源头
File dest = new File(destPath);//目的地
//2、选择流
InputStream is =null;
OutputStream os =null;
try {
is =new FileInputStream(src);
os = new FileOutputStream(dest);
//3、操作 (分段读取)
byte[] flush = new byte[1024]; //缓冲容器
int len = -1; //接收长度
while((len=is.read(flush))!=-1) {
os.write(flush,0,len); //分段写出
}
os.flush();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally{
//4、释放资源 分别关闭 先打开的后关闭
try {
if (null != os) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(null!=is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Java的IO_07文件的拷贝
最新推荐文章于 2024-11-12 18:35:04 发布
本文详细介绍了使用Java进行文件拷贝的方法,通过字节输入输出流实现文件的复制过程,包括创建源文件和目标文件、选择合适的流、分段读取和写入数据,以及最后的资源释放。
1012

被折叠的 条评论
为什么被折叠?



