我最近一直在尝试为我的程序创建一个更新程序。更新程序应该去保管箱,查看“公共(public)”文件夹中的文件,并确定它是否存在。它可以工作,并且可以下载文件,但无法检查文件是否存在。我看到了this我认为这是一个解决方案,但它似乎不起作用。
这是我用来检查文件是否存在的代码:
public static boolean exists(String URLName) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(URLName)
.openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
但是,它似乎总是返回true。我正在访问的文件都以“App_”开头并以“.zip”结尾。唯一不同的是版本,格式为#.###。
这是我如何检查它的完整代码:
public static void main(String[] args) throws IOException,
InterruptedException {
double origVersion = 0.008;
double versionTimes = 0.000;
while(exists("http://dl.dropbox.com/u/.../" + "App_"+ String.valueOf(origVersion + versionTimes) + ".zip")) {
versionTimes = round(versionTimes + 0.001);
//origVersion = round(origVersion + 0.001);
System.exit(0);
}
}
public static boolean exists(String URLName) {
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con = (HttpURLConnection) new URL(URLName)
.openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
static double round(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.###");
return Double.valueOf(twoDForm.format(d));
}
抱歉...该代码太长了。反正。为了对此进行测试,现在它将检查版本 0.009 是否可用。它是什么。它的完整版本在变量 double origVersion 中。现在,如果您将 origVersion 设置为 0.009,它将检查 0.01。这很好,除了 App_0.01.zip 不存在这一事实,但它仍然说它存在!
我也研究了 wget 来解决这个问题,方法是用参数启动 wget
文件名 --no-proxy --spider
但这也没有用。谁能帮我?我将不胜感激。
我还在其他地方看到您可以与该文件建立连接,如果连接安全,则该文件存在。如果没有,它不会。但是,我不知道该怎么做。谁能把我从黑暗中带出来?
[编辑]
此外,在 wget 上运行 THEFILENAME --no-proxy --spider 工作,并在检查版本 0.009 时输出以下内容:
Spider mode enabled. Check if remote file exists.
--2012-03-16 08:59:55-- http://dl.dropbox.com/u/.../....zip
Resolving dl.dropbox.com... 107.21.103.249, 107.20.135.4, 107.20.198.68, ...
Connecting to dl.dropbox.com|107.21.103.249|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 758067 (740K) [application/zip]
Remote file exists.
在检查版本 0.01 时:
Spider mode enabled. Check if remote file exists.
--2012-03-16 09:01:15-- http://dl.dropbox.com/u/.../....zip
Resolving dl.dropbox.com... 107.22.196.64, 50.19.217.32, 174.129.218.194, ...
Connecting to dl.dropbox.com|107.22.196.64|:80... connected.
HTTP request sent, awaiting response... 404 NOT FOUND
Remote file does not exist -- broken link!!!
我还尝试使用 this 读取 wget 的输出,并使用 if(input.indexOf("404 NOT FOUND") == -1),但仍然无济于事。
最佳答案
执行 HEAD
请求绝对是检查远程服务器上是否存在文件的正确方法。
我看不出您的 exists(String URLName)
方法有任何问题,所以我会检查它是否正在传递您认为的 URL。
这一行看起来很奇怪:
versionTimes = round(versionTimes + 0.001);
在检查文件是否存在和打印消息之间,您正在更改 versionTimes
的值。
关于java - 检查远程服务器上的文件,如果存在,则下载它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9737486/