1

I am new to using the streams.I am trying to download zipfile using httpClient in my appliation.when I am downloading the zip file I am getting the sucessfull response from the client.with the response I am trying to generate the zipfile in my local folder using the inputstream.I am able to generating the zip file but there is no content.can somebody help me out here. below is my code snippet.

   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);
               }
        } 
  • What happens if you leave out the `ZipInputStream` and use the `InputStream` of the content directly? Do you get anything then? I think you need at least call `getNextEntry` from the ZIP stream to get any meaningful content, as `ZipInputStream` is reading an entire archive, not a single file. That's an answer, isn't it? I've written it down as one. – Maarten Bodewes Nov 27 '19 at 20:09
  • 2
    tip: you don't need a `ZipInputStream` if your only purpose is to save the stream to file. you should omit `zipInput` and use `fileInput` directly. – jannis Nov 27 '19 at 20:12
  • Marteen, below two lines of code is already downloading the zip file as inputstream but my goal is to generate the zip file in my local with the downloaded content. CloseableHttpResponse response = httpClient.execute(getRequest); InputStream fileInput = response.getEntity().getContent(); – Sudhakar Reddy Nov 27 '19 at 20:31
  • 1
    Firstly generating zip file and download zip file from remote server is totally different things. Also Marteen should give downvote to your question because you didn't read any content from web and your question is not clear. – fuat Nov 27 '19 at 20:44

1 Answers1

2

You need at least call getNextEntry from the ZIP stream to get any meaningful content, as ZipInputStream is reading an entire archive, not a single file. Probably the stream doesn't return any bytes if you are not reading an entry.

Either you unzip the stream, or you can write it directly to file, in which case you don't need the ZipInputStream at all.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263