2

I'd like to use a zip file from remote URL inmemory only, using spring Resource class:

UrlResource url = new UrlResource("https://path.to.TheFile.zip");
System.out.println(url.getFile().lastModified()); //=0, so probably it did not work

Result:

Caused by: java.io.FileNotFoundException: https://path.to.TheFile.zip (The syntax for the filename, directory or media is invalid)
    at java.util.zip.ZipFile.open(Native Method) ~[?:1.7.0_51]
    at java.util.zip.ZipFile.<init>(ZipFile.java:215) ~[?:1.7.0_51]
    at java.util.zip.ZipFile.<init>(ZipFile.java:145) ~[?:1.7.0_51]
    at java.util.zip.ZipFile.<init>(ZipFile.java:159) ~[?:1.7.0_51]

What might be wrong here?

I cannot use url.getInputStream() as I cannot pass the IS into a ZipFile: ZipFile(url.getInputStream()) //error

membersound
  • 81,582
  • 193
  • 585
  • 1,120

1 Answers1

-1

According to getFile()'s javadoc: (emphasis mine)

This implementation returns a File reference for the underlying URL/URI, provided that it refers to a file in the file system.

You should use getInputStream() instead. You could then just store the byte array into a local in-memory data structure (for instance, using StreamUtils.copyToByteArray) and process it (take a look at How can I convert byte array to ZIP file).

In order to use ZipFile as suggested in the edited question, you'd need to write the byte array to a temporary local File (hint: File.createTempFile and FileCopyUtils.copy()), and then instantiate ZipFile straight away from it.

Remember closing the Stream if necessary and deleting the temporary File when you're done with it.

Community
  • 1
  • 1
Xavi López
  • 27,550
  • 11
  • 97
  • 161
  • But `new ZipFile(File file)` can only take a `File` as argument, no item or byte streams... – membersound Feb 13 '15 at 11:20
  • Read the stream into a byte array, save it to a temporary local `File` (hint: [`File.createTempFile`](http://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile%28java.lang.String,%20java.lang.String%29)) and instantiate `ZipFile` straight away from it. Remember closing the `Stream` if necessary and deleting the temporary `File` when you're done with it. – Xavi López Feb 13 '15 at 11:21
  • I want/have to process the file completely inmemory, without saving the file even temporary! – membersound Feb 13 '15 at 11:26
  • 1
    Then what's limiting that requirement is the idea of using `ZipFile`. Most probably there are suitable ways to unzip an in-memory byte array. Take a look for instance at [How to decompress a gzipped data in a byte array?](http://stackoverflow.com/q/270268/851811) or [here](http://www.java2s.com/Tutorial/Java/0180__File/DecompressaByteArray.htm). – Xavi López Feb 13 '15 at 11:30
  • Sorry, the question linked in my last comment applies to `gzip` files, not `zip`. The right question to look into would be [How can I convert byte array to ZIP file](http://stackoverflow.com/a/8367155/851811). – Xavi López Feb 13 '15 at 12:00