按日期删除HDFS数据

转自:http://blog.csdn.net/eryk86/article/details/7472346

  1. import java.io.IOException;  
  2. import java.text.SimpleDateFormat;  
  3. import java.util.Calendar;  
  4. import java.util.HashSet;  
  5. import java.util.Set;  
  6.   
  7. import org.apache.hadoop.conf.Configuration;  
  8. import org.apache.hadoop.fs.FileStatus;  
  9. import org.apache.hadoop.fs.FileSystem;  
  10. import org.apache.hadoop.fs.Path;  
  11. /** 
  12.  *  
  13.  * @author eryk 
  14.  * 
  15.  */  
  16. public class DeleteHDFSFile {  
  17.   
  18.     private FileSystem fs;  
  19.     private Set _delete = new HashSet(); // 记录要删除的路径  
  20.   
  21.     public DeleteHDFSFile(FileSystem fs) {  
  22.         this.fs = fs;  
  23.     }  
  24.       
  25.     /** 
  26.      *  
  27.      * @param args 
  28.      *      args[0] N天内的数据要保留 
  29.      *      args[1] 要删除数据的路径        /run/output/hadoop 
  30.      * @throws Exception 
  31.      */  
  32.     public static void main(String[] args) throws Exception {  
  33.         Configuration _conf = new Configuration();  
  34.         FileSystem fs = FileSystem.get(_conf);  
  35.         DeleteHDFSFile df = new DeleteHDFSFile(fs);  
  36.           
  37.         Calendar calendar = Calendar.getInstance();  
  38.         calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt("-"+args[0]));  
  39.         String date = new SimpleDateFormat("yyyyMMdd").format(calendar.getTime());  
  40.           
  41.         df.fileList(args[1],Integer.parseInt(date));  
  42.           
  43.         for(Path _path: df._delete){  
  44.             if(fs.exists(_path)){  
  45.                 fs.delete(_path);  
  46.             System.out.println("delete:"+_path);  
  47.             }  
  48.         }  
  49.         fs.close();  
  50.     }  
  51.   
  52.     public void fileList(String path,int date) throws IOException{  
  53.         FileStatus[] fileList = fs.listStatus(new Path(path));  
  54.           
  55.         if(fileList == null)return;  
  56.           
  57.         for(FileStatus file : fileList){  
  58.             String _path = file.getPath().toString();  
  59.             if(file.isDir()){  
  60.                 if(_path.matches(".*?\\d{8}?.*")){  
  61.                     String[] _pathDate = _path.split("/");  
  62.                     for(String d : _pathDate){  
  63.                         boolean t = (d.matches("\\d{8}"))? (Integer.parseInt(d)< date)? true : false : false;  
  64.                         if(t){  
  65.                             System.out.println("add delete list :"+ _path);  
  66.                             _delete.add(new Path(_path));  
  67.                         }  
  68.                     }  
  69.                 }  
  70.                 fileList(file.getPath().toString(),date);  
  71.             }  
  72.         }  
  73.     }  
  74. }  

你可能感兴趣的:(hadoop)