hdfs客户端操作
配置HADOOP_HOME环境变量
配置Path环境变量。
在IDEA中创建一个Maven工程HdfsClientDemo,并导入相应的依赖坐标+日志添加
<dependencies> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-client</artifactId> <version>3.1.3</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.30</version> </dependency> </dependencies>
创建HdfsClient类
public class HdfsClient { @Test public void testMkdirs() throws IOException, URISyntaxException, InterruptedException { // 1 获取文件系统 Configuration configuration = new Configuration(); // FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration); FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration,"atguigu"); // 2 创建目录 fs.mkdirs(new Path("/xiyou/huaguoshan/")); // 3 关闭资源 fs.close(); } }
HDFS文件上传
public void testCopyFromLocalFile() throws IOException, InterruptedException, URISyntaxException { // 1 获取文件系统 Configuration configuration = new Configuration(); configuration.set("dfs.replication", "2"); FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "atguigu"); // 2 上传文件 fs.copyFromLocalFile(new Path("d:/sunwukong.txt"), new Path("/xiyou/huaguoshan")); // 3 关闭资源 fs.close(); }
HDFS文件下载
public void testCopyToLocalFile() throws IOException, InterruptedException, URISyntaxException{ // 1 获取文件系统 Configuration configuration = new Configuration(); FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "atguigu"); // 2 执行下载操作 // boolean delSrc 指是否将原文件删除 // Path src 指要下载的文件路径 // Path dst 指将文件下载到的路径 // boolean useRawLocalFileSystem 是否开启文件校验 fs.copyToLocalFile(false, new Path("/xiyou/huaguoshan/sunwukong.txt"), new Path("d:/sunwukong2.txt"), true); // 3 关闭资源 fs.close(); }
HDFS文件更名和移动
public void testRename() throws IOException, InterruptedException, URISyntaxException{ // 1 获取文件系统 Configuration configuration = new Configuration(); FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "atguigu"); // 2 修改文件名称 fs.rename(new Path("/xiyou/huaguoshan/sunwukong.txt"), new Path("/xiyou/huaguoshan/meihouwang.txt")); // 3 关闭资源 fs.close(); }