package test;
/*
* 实现单级文件夹的复制
* 步骤:
* 1. 获取源的文件夹名 getName()方法
* 2. 根据获取到文件夹的名字,在我们的目的磁盘创建出一个相同名称的文件夹
* exists()没有,新建一个文件夹 mkdir()
* 3. 获取源文件夹中的所有文件列表
* File files[] = 源. listFiles();
* 4. 遍历数组,获取到数组中存储的所有文件名
* 5. 获取源文件的文件名
* 6. 使用字节输入流FileInputStream 读取源中的文件
* 7. 将复制文件的目的d:\\demo和源文件名联合起来,组成新的复制目的地
* 8. 用字节输出流,绑定新的赋值目的地
*
*
*
*/
import java.io.*;
public class CopyDirDemo {
public static void main(String[] args) {
File source = new File("c:\\demo");
File target = new File("d:\\");
copyDir(source,target);
}
public static void copyDir(File source,File target){
String dirName = source.getName();//源文件夹名
File newTarget = new File(target,dirName);//d:\\demo
//判断newTarget对象中封装的目录有没有,有就不创建,没有就创建
if(!newTarget.exists())
newTarget.mkdir();
File[] files = source.listFiles();
for(File f : files){
//获取到源文件的文件名、
String fileName = f.getName();
//将源文件名和复制文件的目的文件夹联合起来,组成新的File对象
File targetFile = new File(newTarget,fileName);
//System.out.println(targetFile);
//字节输入流,读取源文件,输出流写入文件
copyFiles(f,targetFile);
}
}
private static void copyFiles(File source,File target){
//字节输入流
FileInputStream fis = null;
FileOutputStream fos = null;
try{
fis = new FileInputStream(source);
fos = new FileOutputStream(target);
//数组缓冲
byte[] buf = new byte[1024];
int len = 0 ;
while((len = fis.read(buf))!=-1){
fos.write(buf, 0, len);
}
}catch(IOException e){
e.printStackTrace();
throw new RuntimeException("复制失败");
}finally{
try{
if(fos!=null)
fos.close();
}catch(IOException e){}
try{
if(fis!=null)
fis.close();
}catch(IOException e){}
}
}
}
java实现文件夹的复制(含代码)
最新推荐文章于 2023-07-24 10:48:57 发布