上一篇介绍了 File 以及 IO流的一些基础知识 那么这一节动手做一个简单版的文件夹拷贝功能
1.定义两个File 一个连接要拷贝的文件路径 一个连接拷贝的目标地点
File src = new File("D:/demo");//要拷贝的文件夹
File to = new File("D:/copyDemo");//拷贝目标地点
demo文件下的文件结构如下 里面包含子包,子包下面也有一些文件
创建好了连接之后下一步就是读写了 因为文件夹层级是不确定的所以要用到递归操作
首先判断要拷贝的文件是否存在
if(!src.exists()){
//判断拷贝 文件/文件夹 是否存在
System.out.println("要拷贝的文件不存在");
return;
}
如果存在接着往下走
再判断他是文件还是文件夹 如果是文件夹的话直接拷贝即可
if(src.isFile()){
//src为要拷贝的文件 第二个参数为拷贝后的文件to.getAbsoluteFile()为要拷贝的目标文件
//夹路径+拷贝的文件名称src.getName()
copyFile(src, new File(to.getAbsoluteFile(),src.getName()));
}
文件拷贝方法如下 为了简洁 所有的异常统一向上抛了
/**
* 文件拷贝方法
* @param src
* @param to
* @throws IOException
*/
public static void copyFile(File src, File to) throws IOException {
InputStream inputStream = new FileInputStream(src);
OutputStream outputStream = new FileOutputStream(to);
byte [] b = new byte[1024];
int lent;
while(-1 != (lent = inputStream.read(b))){
outputStream.write(b,0,lent);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
这个时候文件就可以拷贝完毕了 那如果是文件夹怎么办?
if(src.isDirectory()){
//是文件夹
File[] files = src.listFiles();//获取文件夹下面的所有文件列表
//在目标文件夹路径下创建一个要拷贝的文件夹的链接
to = new File(to.getAbsoluteFile(),src.getName());
//判断目标文件夹是否存在
if(!to.exists()){
//创建文件夹
to.mkdirs();
}
//遍历要拷贝的文件夹下的子文件
for(File file : files){
//每一个文件递归调用当前方法
copyFolder(file, to);
}
}
通过递归调用当前方法可以达到无层级限制的文件拷贝 下面贴出完整代码 有问题欢迎留言反馈!
public static void main(String[] args) throws IOException {
File src = new File("D:/demo");
File to = new File("D:/copyDemo");
if(!src.exists()){
//判断拷贝 文件/文件夹 是否存在
System.out.println("要拷贝的文件不存在");
return;
}
copyFolder(src,to);
}
public static void copyFolder(File src, File to) throws IOException {
//判断是不是文件夹
if(src.isDirectory()){
//是文件夹
File[] files = src.listFiles();//获取文件夹下面的所有文件列表
//在目标文件夹路径下创建一个要拷贝的文件夹的链接
to = new File(to.getAbsoluteFile(),src.getName());
//判断目标文件夹是否存在
if(!to.exists()){
//创建文件夹
to.mkdirs();
}
//遍历要拷贝的文件夹下的子文件
for(File file : files){
//每一个文件递归调用当前方法
copyFolder(file, to);
}
}else if(src.isFile()){
//src为要拷贝的文件 第二个参数为拷贝后的文件to.getAbsoluteFile()为要拷贝的目标文
//件夹路径+拷贝的文件名称src.getName()
copyFile(src, new File(to.getAbsoluteFile(),src.getName()));
}
}
/**
* 文件拷贝方法
* @param src
* @param to
* @throws IOException
*/
public static void copyFile(File src, File to) throws IOException {
InputStream inputStream = new FileInputStream(src);
OutputStream outputStream = new FileOutputStream(to);
byte [] b = new byte[1024];
int lent;
while(-1 != (lent = inputStream.read(b))){
outputStream.write(b,0,lent);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
执行结果如下