gpt4 book ai didi

java - 如何以编程方式写入 HDFS?

转载 作者:可可西里 更新时间:2023-11-01 16:38:04 25 4
gpt4 key购买 nike

因此,经过 36 小时的试验之后,我终于设法启动并运行了一个集群,但现在我很困惑如何使用 Java 向其写入文件?一个教程说应该使用这个程序,但我完全不理解它,它也不起作用。

public class FileWriteToHDFS {

public static void main(String[] args) throws Exception {

//Source file in the local file system
String localSrc = args[0];
//Destination file in HDFS
String dst = args[1];

//Input stream for the file in local file system to be written to HDFS
InputStream in = new BufferedInputStream(new FileInputStream(localSrc));

//Get configuration of Hadoop system
Configuration conf = new Configuration();
System.out.println("Connecting to -- "+conf.get("fs.defaultFS"));

//Destination file in HDFS
FileSystem fs = FileSystem.get(URI.create(dst), conf);
OutputStream out = fs.create(new Path(dst));

//Copy file from local to HDFS
IOUtils.copyBytes(in, out, 4096, true);

System.out.println(dst + " copied to HDFS");

}
}

我的困惑是这段代码如何识别我的集群的细节?它如何知道主节点在哪里以及从节点在哪里?

此外,当我运行此代码并在源中提供一些本地文件并将目标留空/或仅提供文件名时,程序会将文件写回我的本地存储,而不是我为我的名称节点定义为存储空间的位置和数据节点。我应该手动提供这条路径吗?这是如何运作的?请推荐一些可以帮助我更好地理解它或可以使用最小示例的博客。

最佳答案

首先,您需要将一些 Hadoop 库添加到您的类路径中。没有这些,不,该代码将无法工作。

How will it know where the masternode is and where the slavenodes are?

来自 new Configuration(); 和后续的 conf.get("fs.defaultFS")

它读取HADOOP_CONF_DIR 环境变量的core-site.xml 并返回namenode 的地址。客户端只需要与名称节点对话以接收数据节点的位置,从中写入文件 block

the program writes the file back to my local storage

不清楚您在哪里配置了文件系统,但默认是 file://,您的本地磁盘。您可以在 core-site.xml 中更改它。如果你按照 Hadoop 文档,伪分布式集群设置提到了这个

当简单的 hdfs dfs -put 会做同样的事情时,为什么您需要自己的 Java 代码也不是很清楚

关于java - 如何以编程方式写入 HDFS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47766268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com