java批处理,检查数据库中信息和文件夹中文件信息的一致性

 

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();
  }       
  
 }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值