Home > Net >  How to save ZIP file from HttpURLConnection response
How to save ZIP file from HttpURLConnection response

Time:07-29

I am trying to save the zip file i am receiving from a service call . Below is the code i am trying to save it . Am not getting any error but not getting the extension .

ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream("C:\\RandD\\IC");// not allowing 
me to save as IC.zip
FileChannel fileChannel = fileOutputStream.getChannel();
fileOutputStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);

What is the correct way to save the zip file . Looking for most efficient way to do this.

CodePudding user response:

To copy from an URL - pointing to a file, namely a ZIP file - to the file system you can use Files.copy (which exists since Java 7):

try (var is = url.openStream()) {
  Files.copy(is, Path.of("C:/RandD/IC.zip"));
}

This code should work with Java 11 and in Java 8, this could be:

try (InputStream is = url.openStream()) {
  Files.copy(is, Paths.get("C:/RandD/IC.zip"));
}

Even if you want to do something more complicate (eg: open the ZIP file in Java, in which case you can use ... Java NIO2 to do so), you don't need to use channels for that.

  • Related