在HDFS上刪除某個路徑下特定類型的文件,好比class類型文件,好比txt類型文件

一、先獲取鏈接:

public class Utils {

    public static FileSystem HDFS() throws Exception{
        
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS","hdfs://potter2:9000");
        System.setProperty("HADOOP_USER_NAME", "potter");
        FileSystem fs = FileSystem.get(conf);
        return fs;
         
         
    }
}

二、如下是主要代碼apache

package api;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.Test;
/**
 * 刪除某個路徑下特定類型的文件,好比class類型文件,好比txt類型文件
 * @author Administrator
 *
 */
public class Dels {

        
        public static final String TXT = "txt";
        @Test
        public void dels() throws Exception{
            Path path = new Path("/a");
            //獲取鏈接
            FileSystem fs = Utils.HDFS();
            //獲取HDFS上路徑
            FileStatus fileStatus = fs.getFileStatus(path);
            
            boolean directory = fileStatus.isDirectory();
            System.out.println(directory);
            System.out.println("--------------------");
            // 根據該目錄是不是文件或者文件夾進行相應的操做
            if (directory) {
                Directory(path);
            }else {
                Delete(path);
            }
        }
        public void Directory (Path path) throws Exception{
            //獲取鏈接
            FileSystem fs = Utils.HDFS();
            //查看該目錄Path目錄下一級子目錄和子文件的狀態
            FileStatus[] listStatus = fs.listStatus(path);
            //對該目錄進行遍歷,尋找.txt文件
            for(FileStatus fStatus : listStatus){
                Path p = fStatus.getPath();
                System.out.println(p+"***********");
                //若是是文件,而且是以.txt結尾,則刪除,不然繼續遍歷下一級目錄
                if (fStatus.isFile()) {
                    Delete(p);
                }else{
                    Directory(p);
                }
            }
        }
        public void Delete(Path path) throws Exception{
            FileSystem fs = Utils.HDFS();
            //獲取路徑下文件的名稱
            String name = path.getName();
            System.out.println(name);
            
            //判斷是否是以.txt結尾
            int start = name.length() - TXT.length();
            int end = name.length();
            //就得後綴名
            String Suffix = name.substring(start,end);
            if (Suffix.equals(TXT)) {
                fs.delete(path,true);
            }
    }
}
相關文章
相關標籤/搜索