如何从ZipInputStream返回多个文件

时间:2015-03-04 06:52:05

标签: java

我正在从ftp服务器下载一个zip文件。该zip文件包含几个csv文件。我正在尝试提取两个csv文件,以便我可以将它们传递给Opencsv,但我似乎遇到了一些问题。我假设必须有一个更好的方法来处理这个,而不是我在下面的方式。如何返回我的csv文件,以便它们在我的csv阅读器列表中可用?

我的代码

ftp.retrieveFile(file, output);
InputStream inputStream = new ByteArrayInputStream(output.toByteArray());

Map<String, InputStream> inputStreams = new HashMap<>();

if (importTask.isZipfile()) {
    inputStreams.put("products", importUtils.getZipData(new ZipInputStream(inputStream), importTask.getFilename()));

    if(importTask.getCustomerFilename() != null) {
        inputStream = new ByteArrayInputStream(output.toByteArray());
        inputStreams.put("customers", importUtils.getZipData(new ZipInputStream(inputStream), importTask.getCustomerFilename()));
    }
} else {
    inputStreams.put("products", inputStream);
}

ftp.logout();
ftp.disconnect();

return inputStreams;

Zip

public InputStream getZipData(ZipInputStream zip, String filename) throws FileNotFoundException, IOException {
    for (ZipEntry e; (e = zip.getNextEntry()) != null;) {

        if (e.getName().equals(filename)) {
            return zip;
        }
    }
    throw new FileNotFoundException("zip://" + filename);
}

1 个答案:

答案 0 :(得分:0)

如果您使用Java 7+,那么您可以获得更简单的解决方案;你可以使用zip文件系统提供程序。

这是一些示例代码;请注意,您需要.close()生成的InputStreamFileSystem s:

public static void getFsFromZipFile(final Path zipFile)
    throws IOException
{
    final URI uri = URI.create("jar:" + zipFile.toUri());

    final Map<String, ?> env = Collections.singletonMap("readonly", "true");

    return FileSystems.newFileSystem(uri, env);
}

public static getInputStreamFromZip(final FileSystem zipfs, final String name)
    throws IOException
{
    return Files.newInputStream(zipfs.getPath(name));
}

然而,这不是我建议您这样做的方式。我建议的是:

final Map<String, Path> getFilesFromZip(final Path zipFile, final String... names)
    throws IOException
{
    Path tmpfile;

    final URI uri = URI.create("jar:" + zipFile.toUri());

    final Map<String, ?> env = Collections.singletonMap("readonly", "true);

    final Map<String, Path> ret = new HashMap<>();

    try (
        final FileSystem zipfs = FileSystems.newFileSystem(uri, env);
    ) {
        for (final String name: names) {
            tmpfile = Files.createTempFile("tmp", ".csv");
            Files.copy(zipfs.getPath(name), tmpfile);
            ret.put(name, tmpfile);
        }
        return ret;
    }
}