所以我有这个简单的方法来下载和替换文件:
public void checkForUpdates() {
try {
URL website = new URL(downloadFrom);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(downloadTo);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
} catch (IOException e) {
System.out.println("No files found");
}
}
如何检查目的地中是否存在具有特定名称的具体文件(downloadFrom)?现在,如果没有文件,它会下载html页面。
答案 0 :(得分:0)
您可以从标题
获取内容类型URL url = new URL(urlname);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
String contentType = connection.getContentType();
然后检查它的HTML /文本或文件。
答案 1 :(得分:0)
我建议检查代码200的HTTP代码。这些内容如下:
public class DownloadCheck {
public static void main(String[] args) throws IOException {
System.out.println(hasDownload("http://www.google.com"));
System.out.println(hasDownload("http://www.google.com/bananas"));
}
private static boolean hasDownload(String downloadFrom) throws IOException {
URL website = new URL(downloadFrom);
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) website.openConnection();
return connection.getResponseCode() == 200; // You could check other codes though
}
catch (Exception e) {
Logger.getLogger(OffersUrlChecker.class.getName()).log(Level.SEVERE,
String.format("Could not read from %s", downloadFrom), e);
return false;
}
finally {
if (connection != null) {
connection.disconnect(); // Make sure you close the sockets
}
}
}
}
如果您运行此代码,您将获得:
true
false
作为输出。
您可以考虑将代码200以外的其他代码视为正常。请参阅有关HTTP代码here的更多信息。