package cn.itcast_03;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
* 需求:复制单级文件夹
* 复制某个文件夹下的所有文件
*
* 数据源:E:\\demo
* 目的地:E:\\test
*
* 分析:
* A:封装目录
* B:获取该文件夹下的所有文本的File数组
* C:遍历该数组,得到每一个对象
* D;把该File复制
*
*/
public class 复制单级文件夹 {
public static void main(String[] args) throws IOException {
// 封装目录
File srcFolder = new File("E:\\dome");
//封装目的地
File desFolder = new File("E:\\text");
//目的地文件夹不存在,电脑不会自动创建
//所以当文件夹不存在,就创建
if(!desFolder.exists()) {
//检测是否有文件夹
desFolder.mkdirs();//创建文件夹
}
//获取该文件夹下的所有文本的File数组
File[] fileArray = srcFolder.listFiles();
//遍历该File数值,得到每一个File对象
for(File file : fileArray) {
//System.out.println(file);
//数据源:E:\\demo\\1.jpg
//目的地:E:\\test\\1.jpg
String name = file.getName();//1.jpg
File newFile = new File(desFolder,name);//拼接再一起是E:\\test\\1.jpg
copy(file,newFile);
}
}
private static void copy(File file, File newFile) throws IOException {
BufferedInputStream bi = new BufferedInputStream(
new FileInputStream(file));
BufferedOutputStream bo = new BufferedOutputStream(
new FileOutputStream(newFile));
byte[] by = new byte[1024];
int len = 0;
while((len = bi.read(by)) != -1) {
bo.write(by,0,len);
}
bo.close();
}
}
폴더의 모든 파일 복사
추천
출처blog.csdn.net/kaszxc/article/details/108674458
행