【问题标题】:Deleting directories starting with certain name from HDFS in Java在Java中从HDFS中删除以某个名称开头的目录
【发布时间】:2017-06-08 21:18:47
【问题描述】:

我正在尝试使用以下代码从 spark 中删除 hive 阶段文件。此代码可以删除目录中的文件,但我想删除所有以 '.hive-staging_hive' 开头的文件。

我能知道删除以某些文本开头的目录的方法吗?

 Configuration conf = new Configuration();
            System.out.println("560");
            Path output = new Path("hdfs://abcd/apps/hive/warehouse/mytest.db/cdri/.hive-staging_hive_2017-06-08_20-45-20_776_7391890064363958834-1/");
            FileSystem hdfs = FileSystem.get(conf);

            System.out.println("564");

            // delete existing directory
            if (hdfs.exists(output)) {
                System.out.println("568");
                hdfs.delete(output, true);
                System.out.println("570");

            }

【问题讨论】:

  • 我认为您可以使用 shell 脚本轻松完成此操作。你愿意接受 bash 解决方案吗?

标签: hadoop apache-spark hdfs


【解决方案1】:

简单的方法是从Java程序运行一个进程,并使用通配符删除目录中所有以".hive-staging_hive"开头的文件。

String command="hadoop fs -rm pathToDirectory/.hive-staging_hive*";
int exitValue;
try {
    Process process = Runtime.getRuntime().exec(command);
    process.waitFor();
    exitValue = process.exitValue();
}catch (Exception e) {
    System.out.println("Cannot run command");
    e.printStackTrace();
}

下一个方法是列出目录中的所有文件。过滤以 ".hive-staging_hive" 开头的文件并删除。

Configuration conf = new Configuration();

Path path = new Path("hdfs://localhost:9000/tmp");

FileSystem fs = FileSystem.get(path.toUri(), conf);

FileStatus[] fileStatus = fs.listStatus(path);

List<FileStatus> filesToDelete = new ArrayList<FileStatus>();

for (FileStatus file: fileStatus) {

    if (file.getPath().getName().startsWith(".hive-staging_hive")){
        filesToDelete.add(file);
    }
}


for (int i=0; i<filesToDelete.size();i++){
    fs.delete(filesToDelete.get(i).getPath(), true);
}

希望这会有所帮助!

【讨论】:

  • 谢谢尚卡尔。您提到的第二种方法很有帮助。我试过了..但他们没有拉“.hive-staging_hive”目录。我只收到常规分区目录。我能知道他们为什么不拉暂存目录吗?
  • 如果我早先尝试第一种方法,我会收到“未找到 hadoop 命令”错误。我的 Spark 集群在 hadoop 集群之外。可能是我的 spark 程序没有向 hadoop 集群提交“hadoop fs”命令。
  • 你好@AKC 我已经更新了答案的第二部分,它应该可以工作。我也在本地测试过。
  • 它对我有用。谢谢你。在您提到的第二种方法中,我如何使用它来删除带有一些正则表达式的多个文件,例如 _my
猜你喜欢
  • 2018-03-07
  • 1970-01-01
  • 2017-09-19
  • 2010-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多