我正在制作更新程序库的调试版本。通常,更新程序连接到要下载的文件的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
。而且,如果我用Google搜索,似乎什至没有得到任何相关结果-好像人们不使用它。问题是:如何将
FileURLConnection
提供的数据复制到新文件? 最佳答案
你不在乎它是什么。您需要的只是输入流,而URLConnection
提供了该输入流。然后,您只需复制字节。