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

Upload file to HDFS using DFSClient on Java

我正在尝试使用与 Hadoop 捆绑在一起的 DFSClient 将文件 upload/write 发送到我的 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();

此外,类 FileSystemFileUtil.

中还有许多用于在本地和分布式文件系统之间复制文件的有用方法

更改 finally 块顺序

finally {
    if (out != null) {
        out.close();
    }
    if (in != null) {
        in.close();
    }
    if (client != null) {
        client.close();
    }
}