import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Stack;
/*很多系统都会有上传文件,现在这些文件在一个物理目录下,数据库中也有,
但在删除时,只是把库中的这些文件删除了,而目录下的文件并没有被删除,
而导致这个目录下的文件越来越多,我现在要做个java批处理,
大致的意思是判断比较数据库表中的值和目录文件是否一致,库中有,目录没有,报错。
库中没有,目录里有,把目录下的那个删除,都有ok。*/
public class CheckFilebatch {
//private static final String LOG_FILE = "F:/CheckFilebatch.log"; //报错的信息写在这个文件里。
private static final String FILE_HOME = "F:/test_batch/"; //要操作的物理目录
public static void main(String[] args){
//标志位,用来判断数据库中有,而文件夹中没有的文件。1表示正常,0表示文件夹中没有(不正常)
int flag = 0;
//fileListInDB用来存储数据库中读取的文件,并用来做之后的迭代
ArrayList<String> fileListInDB = new ArrayList<String>();
//数据库连接类
ConnMysql conn = new ConnMysql();
ResultSet rs = null;
rs = conn.executeQuery("select file_info from file");
try {
//从数据库中file表读取文件,依次放入fileListInDB
while(rs.next()){
String path = rs.getString("file_info");
//File f = new File(path);
//fileListInDB.add(f.getCanonicalPath());
fileListInDB.add(path);
}
//针对数据库中存在的文件进行循环
for(String path : fileListInDB) {
System.out.println(path);
File home = new File(FILE_HOME);
//栈中存储的都是文件夹
Stack<File> tmpStack = new Stack<File>();
tmpStack.add(home);
while (!tmpStack.isEmpty()) {
File tmp = tmpStack.pop();
File[] childs = tmp.listFiles();
for (int i = 0; i < childs.length; i++) {
File child = childs[i];
//System.out.println(child.getCanonicalPath());
//System.out.println(child.getPath());
//System.out.println(child.getName());
//System.out.println(path);
//如果child是子目录则入栈
if (child.isDirectory()) {
tmpStack.push(child);
}else if(path.equals(child.getName())){
//如果数据库中的文件在文件夹中存在,将标志位置1,表示正常
System.out.println(path + "has been found");
flag = 1;
}else if(fileListInDB.contains(child.getName())){
//如果文件夹中的文件在数据库中存在,则正常
}else{
//不满足以上两种情况,则说明文件夹中的文件在数据库中不存在,将该文件删除
child.delete();
}
}
}
if(flag == 0){
System.out.println(path + "not in the directory");
}
flag = 0;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}