【问题标题】:How to unzip files stored in HDFS using Java, without first copying to the local file system?如何使用 Java 解压缩存储在 HDFS 中的文件,而无需先复制到本地文件系统?
【发布时间】:2016-03-23 14:12:47
【问题描述】:

我们将包含 XML 文件的 zip 文件存储在 HDFS 中。我们需要能够使用 Java 以编程方式解压缩文件并流出包含的 XML 文件。 FileSystem.open 返回一个 FSDataInputStream 但 ZipFile 构造函数只接受 File 或 String 作为参数。我真的不想使用 FileSystem.copyToLocalFile。

是否可以流式传输存储在 HDFS 中的 zip 文件的内容,而无需先将 zip 文件复制到本地文件系统?如果有怎么办?

【问题讨论】:

  • 如何在这里利用 hadoop-streaming。将您的解压缩命令包装为一个脚本,该脚本将 zip 文件的位置作为输入并调用类似 >> yarn jar hadoop-streaming.jar -input -mapper

标签: java hadoop zip hdfs


【解决方案1】:

你好,请找到示例代码,

public static Map<String, byte[]> loadZipFileData(String hdfsFilePath) {
            try {
                ZipInputStream zipInputStream = readZipFileFromHDFS(new Path(hdfsFilePath));
                ZipEntry zipEntry = null;
                byte[] buf = new byte[1024];
                Map<String, byte[]> listOfFiles = new LinkedHashMap<>();
                while ((zipEntry = zipInputStream.getNextEntry()) != null ) {
                    int bytesRead = 0;
                    String entryName = zipEntry.getName();
                    if (!zipEntry.isDirectory()) {
                        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                        while ((bytesRead = zipInputStream.read(buf, 0, 1024)) > -1) {
                            outputStream.write(buf, 0, bytesRead);
                        }
                        listOfFiles.put(entryName, outputStream.toByteArray());
                        outputStream.close();
                    }
                    zipInputStream.closeEntry();
                }
                zipInputStream.close();
                return listOfFiles;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }



protected ZipInputStream readZipFileFromHDFS(FileSystem fileSystem, Path path) throws Exception {
    if (!fileSystem.exists(path)) {
        throw new IllegalArgumentException(path.getName() + " does not exist");
    }
    FSDataInputStream fsInputStream = fileSystem.open(path);
    ZipInputStream zipInputStream = new ZipInputStream(fsInputStream);
    return zipInputStream;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多