【问题标题】:How to generate the ZipFile in java如何在java中生成ZipFile
【发布时间】:2019-11-27 19:51:22
【问题描述】:

我是使用流的新手。我正在尝试在我的应用程序中使用 httpClient 下载 zipfile。当我下载 zip 文件时,我从客户端获得了成功的响应。我正在尝试生成 zipfile使用输入流在我的本地文件夹中。我能够生成 zip 文件,但没有内容。有人可以在这里帮助我。下面是我的代码sn-p。

   String url = CONTANTS.SERVER_LOCATION+"Download/Test/"+ "sudhakar_test.zip";
   HttpGet getRequest = new HttpGet(url);
   CloseableHttpClient httpClient =HttpClientBuilder.create().build();
   try (
          CloseableHttpResponse response = httpClient.execute(getRequest);
          InputStream fileInput = response.getEntity().getContent();
          ZipInputStream zipInput = new ZipInputStream (fileInput);
          FileOutputStream output = new FileOutputStream(new File(fileLocation 
          +"/SudhakarZIP_Test.zip"));
        )
          {
            if (response.getStatusLine().getStatusCode() == 200)
             {          
              byte[] buffer = new byte[1024];
              int length;
              while((length = zipInput.read(buffer,0,buffer.length)) >0)
               {
                    output.write(buffer,0,length);
               }
        } 

【问题讨论】:

  • 如果省略ZipInputStream 并直接使用内容的InputStream 会怎样?那你有什么收获吗?我认为您至少需要从 ZIP 流中调用 getNextEntry 以获取任何有意义的内容,因为 ZipInputStream 正在读取整个存档,而不是单个文件。这是一个答案,不是吗?我已经把它写成了一个。
  • 提示:如果您的唯一目的是将流保存到文件,则不需要ZipInputStream。你应该省略zipInput,直接使用fileInput
  • Marteen,下面两行代码已经将 zip 文件作为输入流下载,但我的目标是使用下载的内容在本地生成 zip 文件。 CloseableHttpResponse 响应 = httpClient.execute(getRequest); InputStream fileInput = response.getEntity().getContent();
  • 首先生成 zip 文件和从远程服务器下载 zip 文件是完全不同的事情。 Marteen 也应该对您的问题投反对票,因为您没有阅读网络上的任何内容并且您的问题不清楚。

标签: java webservice-client fileinputstream fileoutputstream zipinputstream


【解决方案1】:

您至少需要从 ZIP 流中调用 getNextEntry 以获取任何有意义的内容,因为 ZipInputStream 正在读取整个存档,而不是单个文件。如果您没有读取条目,流可能不会返回任何字节。

您可以解压缩流,也可以将其直接写入文件,在这种情况下,您根本不需要ZipInputStream

【讨论】:

    猜你喜欢
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 2019-08-14
    • 2014-09-17
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多