复制目标文件夹下内容到指定目录下
需求:在目录1下创建了一批文件夹库,判断目录2下是否存在文件夹,不存在就创建并从文件夹库中随机选择一个文件复制里面的图片
- 读取源文件目录判断文件夹是否存在
private static String isFolder1(String imgPathName,
String imgPathNameId,
String city,
String county,
HcxxInfo hcxxInfo,
HcxxInfo hcxxInfoMsg,
HcxxInfoMapper baseMapper) {
File filePathName = new File(imgPathName);
File filePathNameId = new File(imgPathNameId);
// 村民名称文件夹存在返回路径
if (filePathName.exists()) {
return imgPathName;
// 村民名称+身份证文件夹 返回路径
} else if (filePathNameId.exists()) {
return imgPathNameId;
// 未找到村民文件夹
} else {
filePathName.mkdirs();
String ku = "XXX/XXX";
File file = new File(ku);
File[] fileList = file.listFiles();
int a = random1();
CopyUtils copy = new CopyUtils();
// 设置来源去向
copy.dirFrom = fileList[a];
System.out.println("from:" + fileList[a]);
copy.dirTo = filePathName;
System.out.println("a : "+ a);
copy.listFileInDir(fileList[a]);
// copy(fileList[a],filePathName);
isFolder1(imgPathName,imgPathNameId,city,county,hcxxInfo,hcxxInfoMsg,baseMapper);
System.out.println("===================================");
System.out.println(city + "," + county + "," + imgPathName + "创建成功");
}
return imgPathName;
}
- 复制文件类 CopyUtils
public class CopyUtils {
public static File dirFrom;
public static File dirTo;
// 目标路径创建文件夹
public void listFileInDir(File file) {
File[] files = file.listFiles();
for (File f : files) {
String tempfrom = f.getAbsolutePath();
String tempto = tempfrom.replace(dirFrom.getAbsolutePath(),
dirTo.getAbsolutePath()); // 后面的路径 替换前面的路径名
if (f.isDirectory()) {
File tempFile = new File(tempto);
tempFile.mkdirs();
listFileInDir(f);
} else {
System.out.println("源文件:" + f.getAbsolutePath());
//
int endindex = tempto.lastIndexOf("/");// 找到"/"所在的位置
String mkdirPath = tempto.substring(0, endindex);
File tempFile = new File(mkdirPath);
tempFile.mkdirs();// 创建立文件夹
System.out.println("目标点:" + tempto);
copy1(tempfrom, tempto);
}
}
}
/**
* 封装好的文件拷贝方法
*/
public static void copy1(String from, String to) {
try {
InputStream in = new FileInputStream(from);
OutputStream out = new FileOutputStream(to);
byte[] buff = new byte[1024];
int len = 0;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 随机数
private static int random1() {
Random random = new Random();
int s = random.nextInt(15);
return s;
}