代码之家  ›  专栏  ›  技术社区  ›  user405398

如何将InputStream转换为ZIP格式?

  •  1
  • user405398  · 技术社区  · 15 年前

    我有一个InputStream对象,它实际上是一个zip文件。我想把它改回zip文件并保存。我正在使用DWR的FileTransfer类对象从客户端接收上传的数据。

    FileTransfer 有三种方法, getInputStream()

    在我的例子中,fileTransfer对象包含zip文件以及InputStream对象。 我在谷歌做了很多搜索。但是我找不到一个示例,它演示了InputStream到zip的转换。

    更新

    String zipName = file.getName();
    String zipType = file.getMimeType();
    InputStream zipStream = file.getInputStream();
    ZipInputStream zis = new ZipInputStream(zipStream);
    System.out.println("File Name: "+zipName+"\n"+"File Type: "+zipType);
    int c;
    File f2 = new File(DATA_STORE_LOC+dat+".zip");
    path.setPath2(DATA_STORE_LOC+dat+".zip");
    FileOutputStream fos = new FileOutputStream(f2);
    ZipOutputStream zos = new ZipOutputStream(fos);
    c = zis.read();
    System.out.println(c);
    while ((c = zis.read(BUFFER)) != -1) {
    zos.write(BUFFER, 0, c);
    }
    zos.close();
    zis.close();
    

    java.util.zip.ZipException: ZIP file must have at least one entry .

    3 回复  |  直到 15 年前
        1
  •  4
  •   extraneon    15 年前

    请参阅示例java2s, input output

    为了清楚起见 this input example 你应该这样做:

    // FileInputStream fin = new FileInputStream(args[i]);
    ZipInputStream zin = new ZipInputStream(ft.getInputStream());
    

    static IOUtils.copy(in, out) 复制文件。

    此外,如果您确实希望提取ZIP文件内容,则不应直接复制字节。ZIP文件有一个结构,您可以从ZIP文件中提取条目,而不仅仅是字节(请参见示例)。每个条目都是一个(压缩)文件(或其数据),其原始名称为:

    ZipEntry ze = null;
    while ((ze = zin.getNextEntry()) != null) {
      System.out.println("Unzipping " + ze.getName());
      FileOutputStream fout = new FileOutputStream(ze.getName());
      for (int c = zin.read(); c != -1; c = zin.read()) {
      ...
    

    请注意 javadoc of getNextEntry()

    读取下一个ZIP文件条目并将流定位在条目数据的开头。

    这种定位对于获取压缩文件内容(而不是元数据)至关重要。

    c = zis.read(); // removing the first
    while ((c = zis.read(BUFFER)) != -1) { // so you start with the second?
    

    我相信你混合了两个成语:

    c = zis.read();
    while(c != -1) {
       ...
       c = zis.read();
    }
    

    int c;
    while ((c = zis.read(BUFFER)) != -1) { // so you start with the second?
      ...
    }
    

    我想你可以看出区别:)

        2
  •  3
  •   Don Roby    15 年前

    如果您的输入是 InputStream 输入流 写信给 FileOutputStream

    ZipInputStream 如果必须将zip文件的内容提取为单独的文件(即以编程方式解压缩),则非常有用。在另一边, ZipOutputStream 如果您有内容并且需要将其合并到zip文件中,则使用。