背景:昨天做了一个工作,将数据库里的某张表的字段取出,其字段为file_name,对比数据库的文件名称和 我本地的一个文件夹下的文件名称,文件夹内的文件没有在数据库中一file_name显示则删除该文件,下面是我写的demo,还附带了一些其他的业务逻辑:
被注释掉的部分是string的一些字符串操作,在readAndDelete方法里有用到delete方法删除文件,
public class DeletePicFromFolder {
public static void main(String[] args) {
long startTime=System.currentTimeMillis();
readAndDelete();
long endTime=System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: "+(endTime-startTime)+"ms");
// String s = "http://fsnrec.com:8080/portal/market/SWT-20138121/SWT-2013812120140119142120111.jpg";
// String s1= s.replaceAll("http://fsnrec.com:8080/portal/", "G:/temp/log/");
// System.out.println(s1);
// String[] ss = s.split("/");
// System.out.println(ss.length);
// for(int i=0;i<ss.length;i++){
// System.out.println(ss[i]);
// }
}
public static void readAndDelete() {
String path = "G:/temp/log";
File file = new File(path);
File[] tempList = file.listFiles();
// System.out.println("该目录下对象个数:" + tempList.length);
String sql = "SELECT tt.FILE_NAME FROM t_test_resource tt INNER JOIN t_test_product_to_resource tp on tp.RESOURCE_ID=tt.RESOURCE_ID ";
Result rs = DBConnection.getSelected(sql);
if (rs != null && rs.getRowCount() > 0) {
for (int i = 0; i < tempList.length; i++) {
System.out.println("長度:" + rs.getRowCount());
for (int j = 0; j < rs.getRowCount(); j++) {
ImgInfo imgInfo = new ImgInfo(rs.getRows()[j]);
System.out.println("文件 名稱:" + imgInfo.getImgName());
if (tempList[i].getName() != imgInfo.getImgName()) {
tempList[i].delete();
}
}
}
}
}
}