使用Java下载Zip文件,当它打开时说无法打开。 想知道什么是pblm? 是因为记忆力较少吗?
以下是下载zipFiles的代码
try {
for(int i=0;i<URL_LOCATION.length;i++) {
url = new URL(URL_LOCATION[i]);
connection = url.openConnection();
stream = new BufferedInputStream(connection.getInputStream());
int available = stream.available();
b = new byte[available];
stream.read(b);
File file = new File(LOCAL_FILE[i]);
OutputStream out = new FileOutputStream(file);
out.write(b);
}
} catch (Exception e) {
System.err.println(e.toString());
}
Soln for this:Refered Link is How to download and save a file from Internet using Java?
BufferedInputStream in = null;
FileOutputStream fout = null;
try
{
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(filename);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1)
{
fout.write(data, 0, count);
}
}
finally
{
if (in != null)
in.close();
if (fout != null)
fout.close();
}
答案 0 :(得分:2)
您正在使用available() - 调用来确定要读取的字节数。这是明显错误的(详情请参阅InputStream的javadoc)。 available()仅告诉您可立即获得的数据,而不是实际的流长度。
你需要一个循环并从流中读取,直到它返回-1(对于EndOfStream)作为读取的字节数。
我建议您查看有关流的教程:http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html