简体   繁体   English

如何使用Spring资源从远程URL读取zip文件?

[英]How to read a zip file from remote URL using spring resource?

I'd like to use a zip file from remote URL inmemory only, using spring Resource class: 我只想使用spring Resource类从远程URL内存中使用一个zip文件:

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 我无法使用url.getInputStream()因为无法将IS传递到ZipFile中: ZipFile(url.getInputStream()) //error

According to getFile() 's javadoc : (emphasis mine) 根据getFile()javadoc :(强调我的)

This implementation returns a File reference for the underlying URL/URI, provided that it refers to a file in the file system . 如果该实现引用了文件系统中的文件,则此实现返回针对底层URL / URI的File引用。

You should use getInputStream() instead. 您应该改用getInputStream() 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 ). 然后,您可以将字节数组存储到本地内存数据结构中(例如,使用StreamUtils.copyToByteArray )并进行处理(看看如何将字节数组转换为ZIP文件 )。

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. 为了按照已编辑的问题中的建议使用ZipFile ,您需要将字节数组写入临时的本地File(提示: File.createTempFileFileCopyUtils.copy() ),然后直接实例化ZipFile。

Remember closing the Stream if necessary and deleting the temporary File when you're done with it. 请记住,必要时关闭Stream,并在完成后删除临时文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM