Java - 从 url 下载 zip 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16943102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Download zip file from url
提问by BkSouX
I have a problem with downloading a zip file from an url. It works well with firefox but with my app I have a 404.
我在从 url 下载 zip 文件时遇到问题。它适用于 Firefox,但对于我的应用程序,我有一个 404。
Here is my code
这是我的代码
URL url = new URL(reportInfo.getURI().toString());
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
// Check for errors
int responseCode = con.getResponseCode();
InputStream inputStream;
if (responseCode == HttpURLConnection.HTTP_OK) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}
OutputStream output = new FileOutputStream("test.zip");
// Process the response
BufferedReader reader;
String line = null;
reader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = reader.readLine()) != null) {
output.write(line.getBytes());
}
output.close();
inputStream.close();
Any idea ?
任何的想法 ?
回答by VGR
In Java 7, the easiest way to save a URL to a file is:
在 Java 7 中,将 URL 保存到文件的最简单方法是:
try (InputStream stream = con.getInputStream()) {
Files.copy(stream, Paths.get("test.zip"));
}
回答by Jon Skeet
As for why you're getting a 404 - that hard to tell. You should check the value of url
, which as greedybuddha says, you should get via URI.getURL()
. But it's also possible that the server is using a user agent check or something similar to determine whether or not to give you the resource. You could try with something like cURLto fetch in programmatic way but without having to write any code yourself.
至于为什么您会收到 404 - 很难说。您应该检查 的值url
,正如 greedybuddha 所说,您应该通过URI.getURL()
. 但也有可能服务器正在使用用户代理检查或类似的东西来确定是否为您提供资源。您可以尝试使用cURL 之类的东西以编程方式获取,而无需自己编写任何代码。
However, there another problem looming. It's a zip file. That's binary data. But you're using InputStreamReader
, which is designed for textcontent. Don't do that. You should neveruse a Reader
for binary data. Just use the InputStream
:
然而,另一个问题迫在眉睫。这是一个压缩文件。那是二进制数据。但是您正在使用InputStreamReader
,这是专为文本内容设计的。不要那样做。你永远不应该Reader
对二进制数据使用 a 。只需使用InputStream
:
byte[] buffer = new byte[8 * 1024]; // Or whatever
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) > 0) {
output.write(buffer, 0, bytesRead);
}
Note that you should close the streams in finally
blocks, or use the try-with-resources statement if you're using Java 7.
请注意,您应该在finally
块中关闭流,或者如果您使用的是 Java 7,则使用 try-with-resources 语句。