提供一个HDFS内的文件的路径,对该文件进行创建和删除操作。如果文件所在目录不存在,则自动创建目录。

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.fs.*;

import java.io.*;

 

public class RemoveOrMake {

     /**

     * 判断路径是否存在

     */

    public static boolean test(Configuration conf, String path) {

        try (FileSystem fs = FileSystem.get(conf)) {

            return fs.exists(new Path(path));

        } catch (IOException e) {

            e.printStackTrace();

            return false;

        }

    }

 

    /**

     * 创建目录

     */

    public static boolean mkdir(Configuration conf, String remoteDir) {

        try (FileSystem fs = FileSystem.get(conf)) {

            Path dirPath = new Path(remoteDir);

            return fs.mkdirs(dirPath);

        } catch (IOException e) {

            e.printStackTrace();

            return false;

        }

    }

 

    /**

     * 创建文件

     */

    public static void touchz(Configuration conf, String remoteFilePath) {

        Path remotePath = new Path(remoteFilePath);

        try (FileSystem fs = FileSystem.get(conf)) {

            FSDataOutputStream outputStream = fs.create(remotePath);

            outputStream.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

 

    /**

     * 删除文件

     */

    public static boolean rm(Configuration conf, String remoteFilePath) {

        Path remotePath = new Path(remoteFilePath);

        try (FileSystem fs = FileSystem.get(conf)) {

            return fs.delete(remotePath, false);

        } catch (IOException e) {

            e.printStackTrace();

            return false;

        }

    }

 

    /**

     * 主函数

     */

    public static void main(String[] args) {

        Configuration conf = new Configuration();

        conf.set("fs.defaultFS", "hdfs://localhost:9000");

        String remoteFilePath = "/user/hadoop/dir3/test.txt"; // HDFS路径

        String remoteDir = "/user/hadoop/dir3"; // HDFS路径对应的目录

 

        try {

            /* 判断路径是否存在,存在则删除,否则进行创建 */

            if (RemoveOrMake.test(conf, remoteFilePath)) {

                RemoveOrMake.rm(conf, remoteFilePath); // 删除

                System.out.println("删除文件: " + remoteFilePath);

            } else {

                if (!RemoveOrMake.test(conf, remoteDir)) { // 若目录不存在,则进行创建

                    RemoveOrMake.mkdir(conf, remoteDir);

                    System.out.println("创建文件夹: " + remoteDir);

                }

                RemoveOrMake.touchz(conf, remoteFilePath);

                System.out.println("创建文件: " + remoteFilePath);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

 

}

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值