-1
我需要從一個URL下載zip文件。下面是我寫的代碼:編寫用於下載zip文件的代碼時出現I/O錯誤
package Sample2;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class MonthlyDB1 {
public static void main(String[] args) throws IOException {
URLConnection con = null;
//int i;
try {
Authenticator.setDefault(new CustomAuthenticator());
URL url = new URL("http://www.g1.com/Support/download.asp?fn=2LL\\ASCII\\2LL092015_200.zip&type=db&asset=1-JOKWT&dbAsset=1-JOKY2");
ZipFile zipFile = new ZipFile("http://dl.g1.com/Release/databases/DPV/OPEN_SYSTEM/DPV102015_200.ZIP");
File file= new File("Desktop\\DPV.zip");
//BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())
con = url.openConnection();
BufferedInputStream bis = new BufferedInputStream(
con.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file.getName()));
Enumeration en = zipFile.entries();
while(en.hasMoreElements()){
ZipEntry entry = (ZipEntry)en.nextElement();
String entryName = entry.getName();
long compressedSize = entry.getCompressedSize();
byte[] b = new byte[(int) compressedSize];
int count;
while ((count = bis.read(b)) > 0) {
bos.write(b, 0, count);
}}
bos.flush();
bis.close();
}
catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
}
public static class CustomAuthenticator extends Authenticator {
protected PasswordAuthentication getPasswordAuthentication() {
String prompt = getRequestingPrompt();
String hostname = getRequestingHost();
InetAddress ipaddr = getRequestingSite();
int port = getRequestingPort();
String username = "stov1jypf6";
String password = "1jypf6";
// Return the information (a data holder that is used by Authenticator)
return new PasswordAuthentication(username, password.toCharArray());
}
}
}
但是下面是我得到的錯誤;
I/O錯誤:HTTP:\ dl.g1.com \發佈\數據庫\ DPV \ OPEN_SYSTEM \ DPV102015_200.ZIP(文件名,目錄名或卷標語法不正確)
您似乎試圖打開名稱實際上是URL的ZipFile。 「ZipFile」只適用於文件,不適用於URL。此外,您似乎試圖從「ZipFile」中讀取條目,但是從URL連接中讀取數據。他們不相關,所以你如何期待這個工作? – RealSkeptic