代码

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;

import java.util.stream.Stream;

/**

* Created by maoyu on 18/6/29.

*/

public class DeleteFilesInDir {

private static int totleDeleteFiles =0;

public static void main(String[] args) {

Path rootPath = Paths.get("/Users/maoyu/Movies/aaaa");

dealWithThePath(rootPath);

System.out.println("finish delete, total delete files:" +totleDeleteFiles);

}

private static void dealWithThePath(Path path) {

boolean thisLevelHasDir =false;

boolean thisLevelHasJpg =false;

try {

Object[] objects = Files.list(path).toArray();

for (Object obj : objects) {

Path subPath = (Path)obj;

if (subPath.toString().endsWith(".jpg")) {

thisLevelHasJpg =true;

continue;

}

boolean isDirectory = Files.isDirectory(subPath);

if (isDirectory) {

thisLevelHasDir =true;

dealWithThePath(subPath);

}

}

// 只有这一层里面没有目录文件,并且存在jpg结尾的图片,说明这个目录里要处理

            if (!thisLevelHasDir && thisLevelHasJpg) {

List list =new ArrayList<>();

for (Object obj : objects) {

list.add(obj.toString());

}

Collections.sort(list,new Comparator() {

@Override

                    public int compare(String o1, String o2) {

if (o1.compareTo(o2)>0)return 1;

else return -1;

}

});

int k=0;

for (String str : list) {

k++;

if (k>3)break;

Path deletePath = Paths.get(str);

Files.delete(deletePath);

totleDeleteFiles++;

}

}

}catch(Exception e)  {

e.printStackTrace();

}

}

}

你可能感兴趣的:(代码)