@Test
void contextLoads() throws IOException {
copyDir("f:\\tupian","g:\\tupian");
// 删除上级目录
delFile("f:\\tupian");
}
static String[] imageExtension = new String[]{"jpeg", "jpg", "bmp", "png"};
public static void copyDir(String sourcePath, String newPath) throws IOException {
File file = new File(sourcePath); //获取文件夹File对象
String[] filePath = file.list(); //获取文件夹下所有内容的名称
//创建文件夹
createFile(new File(newPath));
for (int i = 0; i < filePath.length; i++) { //循环遍历
String path = sourcePath + file.separator + filePath[i];
File newFile = new File(path);
//判断是不是文件夹,是的话执行递归。file.separator 分隔符,如“/”
if (newFile.isDirectory()) {
copyDir(path, newPath + file.separator + filePath[i]);
}
//判断是不是文件,是的话旧的文件拷至新的文件夹下
if (newFile.isFile()) {
for (String s : imageExtension) {
if (filePath[i].substring(filePath[i].lastIndexOf(".") + 1).toLowerCase().equals(s)) {
copyFile(sourcePath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
}
}
}
}
delSpecifyTheTypeFile(sourcePath);
}
public static void copyFile(String oldPath, String newPath) throws IOException {
//获取旧的文件File对象
File oldFile = new File(oldPath);
//获取新的文件File对象并生成文件
File file = new File(newPath);
FileInputStream in = new FileInputStream(oldFile);
FileOutputStream out = new FileOutputStream(file);
byte[] buffer=new byte[2097152];
int readByte = 0;
//读取旧文件的流写入新文件里
while((readByte = in.read(buffer)) != -1){
out.write(buffer, 0, readByte);
}
in.close();
out.close();
}
/**
* 判断文件是否存在,不存在就创建
* @param file
*/
public static void createFile(File file) {
if (file.exists()) {
System.out.println("File exists");
} else {
//getParentFile() 获取上级目录(包含文件名时无法直接创建目录的)
if (!file.getParentFile().exists()) {
//创建上级目录
file.getParentFile().mkdirs();
}
file.mkdirs();
}
}
/**
* 删除指定目录下面指定文件类型的文件
*
* @param path
*/
public static void delSpecifyTheTypeFile(String path) {
File dir = new File(path);
if(dir.isDirectory()&&dir.exists()){
// 该文件目录下文件全部放入数组
File[] files = dir.listFiles();
if(files==null || files.length==0){
dir.delete();
}else{
for (File file : files) {
if(file.isFile()&&file.exists()){
file.delete();
}else if(file.isDirectory()&&file.exists()){
delSpecifyTheTypeFile(file.getPath());
}
}
}
}else if(dir.isFile()&&dir.exists()){
dir.delete();
}
}
public static void delFile(String path) {
File file = new File(path);
if(file.isDirectory()){
File[] files = file.listFiles();
//判断文件夹为空
if(files==null || files.length<=0) {
delSpecifyTheTypeFile(path);
}
}
}