我正在制作我的更新程序库的调试版本。通常,更新程序连接到要下载的文件的URL。旧代码看起来像这样:
HttpURLConnection httpConnection;
URL downloadLink = "...";
System.out.println("Downloading update: "+downloadLink);
try {
httpConnection = (HttpURLConnection) (downloadLink.openConnection());
}
catch(IOException e) {
updater.dispatchEvent("download.stopped",ex);
return;
}
问题是,如果链接指向文件(file:/C:/.../file.zip
),则downloadLink.openConnection()
会返回FileURLConnection
而不是HttpURLConnection
。所以我修改了代码以使其更加灵活:
URLConnection connection = null;
try {
connection = downloadLink.openConnection();
} catch (IOException ex) {
updater.dispatchEvent("download.stopped",ex);
}
System.out.println("Downloading update: "+downloadLink);
if(connection instanceof HttpURLConnection) {
// HTTp downloading code exported to different method
if(!download_http((HttpURLConnection) connection, updater))
return false;
}
else if(connection instanceof FileURLConnection) {
throw new UnsupportedOperationException("Now what?");
}
else {
updater.dispatchEvent("download.stopped",
new IllegalStateException("Unknown class type for download conenction: "
+ connection.getClass().getName()));
return false;
}
但我不知道如何使用FileURLConnection
。如果我谷歌它,我似乎甚至没有得到任何相关的结果 - 看起来人们不会使用它。
问题是:如何将FileURLConnection
提供的数据复制到新文件?
答案 0 :(得分:2)
你不在乎它是什么。您只需输入流,URLConnection
即可。然后你只需复制字节。