gpt4 book ai didi

java - 在 Java 上使用 DFSClient 将文件上传到 HDFS

转载 作者:可可西里 更新时间:2023-11-01 16:49:06 26 4
gpt4 key购买 nike

我正在尝试使用与 Hadoop 捆绑在一起的 DFSClient 将文件上传/写入我的 HDFS,但是我没有成功,以下代码实际上在 HDFS 中创建了文件,但它是空的(大小为 0),得到文件并看到它的内容我可以确认它是空的。

如何调试此行为?我已经确认我的本地文件“dilox.txt”包含文本,并且我的缓冲区循环确实在迭代,我的理论是 client.create() 创建的输出缓冲区不会将任何内容发送回 HDFS。

请注意,我不是在 Hadoop 作业中运行它,而是在外部运行它。

相关代码:

String hdfsUrl = "hdfs://1.2.3.4:8020/user/hadoop";

Configuration conf = new Configuration();
conf.set("fs.defaultFS", hdfsUrl);
DFSClient client = new DFSClient(new URI(hdfsUrl), conf);


OutputStream out = null;
InputStream in = null;
try {
out = new BufferedOutputStream(client.create(destinationFilename, true));
in = new BufferedInputStream(new FileInputStream("dilox.txt"));

byte[] buffer = new byte[1024];

int len = 0;
while ((len = in.read(buffer)) > 0) {
System.out.println(buffer.toString());
out.write(buffer, 0, len);
}
} finally {
if (client != null) {
client.close();
}
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}

最佳答案

不能说用 DFSClient 复制文件,但你可以使用 FileSystem用于该目的的方法:

  • copyFromLocalFile(Path src, Path dst) - 从本地文件复制文件系统到 HDFS
  • moveFromLocalFile(Path src, Path dst) - 移动文件本地文件系统到 HDFS

例如:

FileSystem fs = FileSystem.get(conf);
fs.copyFromLocalFile(new Path("/home/user/test.txt"), new Path("/hadoop/test.txt"));

你也可以通过输出流写入文件:

FSDataOutputStream outStream = fs.create(new Path("/hadoop/test.txt"));
outStream.write(buffer);
outStream.close();

此外,在类FileSystem 中还有许多用于在本地和分布式文件系统之间复制文件的有用方法。和 FileUtil .

关于java - 在 Java 上使用 DFSClient 将文件上传到 HDFS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34297358/

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