HDFS的客户端操作(2)文件上传

发布于:2025-05-14 ⋅ 阅读:(9) ⋅ 点赞:(0)

我们向/maven下上传一个文件。 要用到的api是put (或者copyFormLocalFile)。核心代码如下。

public void testCopyFromLocalFile() throws IOException, InterruptedException, URISyntaxException {
    // 1 获取文件系统
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "root");

    // 2 上传文件
    fs.copyFromLocalFile(new Path("d:/sunwukong.txt"), new Path("/maven"));
    // 3 关闭资源
    fs.close();
}

上传结束之后,回到hdfs的UI界面去检查是否成功。

动态设置副本份数(参数优先级)

默认情况下,上传的文件会被保存3份,如果需要的话,我们可以随时去修改这个设置参数。

参数优先级排序(1)客户端代码中设置的值 >(2然后是服务器的自定义配置xxx-site.xml >3)服务器的默认配置(xxx-default.xml

参考代码如下:

@Test
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, "root");
    // 2 上传文件
    fs.copyFromLocalFile(new Path("d:/sunwukong.txt"), new Path("/xiyou/huaguoshan"));
    // 3 关闭资源
    fs.close();
}

修改这个值之后,我们再去重新上传一个新的文件,并检查是否在hdfs的UI面板中能看到这个数值的变化。

HDFS文件下载

接下来,我们看如何去下载文件。这个过程需要调用copyToLocalFile这个API。具体的测试代码如下:

@Test
public void testCopyToLocalFile() throws IOException, InterruptedException, URISyntaxException{

    // 1 获取文件系统
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "root");
    
    // 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();
}

注意:如果执行上面代码,下载不了文件,有可能是你电脑的微软支持的运行库少,需要安装一下微软运行库。