记录实验6

该代码示例展示了如何使用Hadoop的HDFSAPI进行文件系统操作,包括检查路径是否存在、创建目录、创建文件以及删除文件。程序首先配置HDFS连接,然后判断指定路径是否已存在,如果存在则删除,否则创建目录和文件。最后,它在HDFS上创建一个文件。
摘要由CSDN通过智能技术生成

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import java.io.*;

public class HDFSApi {
 /**
 * 判断路径是否存在
 */
 public static boolean test(Configuration conf, String path) throws IOException {
 FileSystem fs = FileSystem.get(conf);
 return fs.exists(new Path(path));
 }
 /**
 * 创建目录
 */
 public static boolean mkdir(Configuration conf, String remoteDir) throws IOException {
 FileSystem fs = FileSystem.get(conf);
 Path dirPath = new Path(remoteDir);
 boolean result = fs.mkdirs(dirPath);
 fs.close();
 return result;
 }
 /**
 * 创建文件
 */
 public static void touchz(Configuration conf, String remoteFilePath) throws IOException {
 FileSystem fs = FileSystem.get(conf);
 Path remotePath = new Path(remoteFilePath);
 FSDataOutputStream outputStream = fs.create(remotePath);
 outputStream.close();
 fs.close();
 }

 /**
 * 删除文件
 */
 public static boolean rm(Configuration conf, String remoteFilePath) throws IOException {
 FileSystem fs = FileSystem.get(conf);
 Path remotePath = new Path(remoteFilePath);
 boolean result = fs.delete(remotePath, false);
 fs.close();
 return result;
 }

public static void main(String[] args) {
Configuration conf = new Configuration();
 conf.set("fs.default.name","hdfs://localhost:9000");
String remoteFilePath = "/user/hadoop/input/text.txt"; // HDFS 路径
String remoteDir = "/user/hadoop/input"; // HDFS 路径对应的目录
try {
/* 判断路径是否存在,存在则删除,否则进行创建 */
if ( HDFSApi.test(conf, remoteFilePath) ) {
HDFSApi.rm(conf, remoteFilePath); // 删除
System.out.println("删除路径: " + remoteFilePath);
} else {
if ( !HDFSApi.test(conf, remoteDir) ) { // 若目录不存在,则进行创建
HDFSApi.mkdir(conf, remoteDir);
System.out.println("创建文件夹: " + remoteDir);
}
HDFSApi.touchz(conf, remoteFilePath);
System.out.println("创建路径: " + remoteFilePath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值