如何使用Java解压缩存储在HDFS中的文件,而无需首先复制到本地文件系统



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

是否可以在不首先将zip文件复制到本地文件系统的情况下流式传输存储在HDFS中的zip文件的内容?如果是,怎么办?

Hi请找到样本代码,

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;
}

相关内容

最新更新