黑猴子的家:API 操作 HDFS 文件上传

1、Code -> GitHub

https://github.com/liufengji/hadoop_hdfs.git

2、Code

    @Test
    public void putFileToHDFS() throws Exception{
        // 1 创建配置信息对象
        // new Configuration();的时候,它就会去加载jar包中的hdfs-default.xml
        // 然后再加载classpath下的hdfs-site.xml
        Configuration configuration = new Configuration();

        // 2 设置参数 
        // 参数优先级: 1、客户端代码中设置的值  2、classpath下的用户自定义配置文件 3、服务器的默认配置
        configuration.set("dfs.replication", "2");

        FileSystem fs = FileSystem.get(new URI("hdfs://node1:9000"),configuration, "victor");
        
        // 3 创建要上传文件所在的本地路径
        Path src = new Path("e:/hello.txt");
        
        // 4 创建要上传到hdfs的目标路径
        Path dst = new Path("hdfs://node1:9000/user/victor/hello.txt");
        
        // 5 拷贝文件
        fs.copyFromLocalFile(src, dst);

        // 6 关闭资源
        fs.close(); 
}

3、将core-site.xml拷贝到项目的根目录下

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>

    <!-- 指定HDFS中NameNode的地址 -->
    <property>
        <name>fs.defaultFS</name>
        <value>hdfs://node1:9000</value>
    </property>

</configuration>

4、将hdfs-site.xml拷贝到项目的根目录下

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<configuration>

    <property>
        <name>dfs.replication</name>
         <value>1</value>
    </property> 

</configuration>

5、测试参数优先级

优先级:客户端代码中设置的值 > classpath下的用户自定义配置文件 > 服务器的默认配置

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容