1. 程式人生 > >在HDFS上刪除某個路徑下特定類型的文件,比如class類型文件,比如txt類型文件

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

繼續 是否 rop 後綴 api tst exc star ret

1、先獲取連接:

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

2、以下是主要代碼

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

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