java 我可以检查一个文件是否存在于一个 URL 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2461864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:17:30  来源:igfitidea点击:

can I check if a file exists at a URL?

javahttp

提问by senzacionale

can I check if a file exists at a URL?

我可以检查一个文件是否存在于一个 URL 中?

This link is very good for C#, what about java. I serach but i did not find good solution.

这个链接对C#很好,java呢。我搜索但我没有找到好的解决方案。

回答by

It's quite similar in Java. You just need to evaluate the HTTP Response code:

它在 Java 中非常相似。您只需要评估 HTTP 响应代码:

final URL url = new URL("http://some.where/file.html");
url.openConnection().getResponseCode();

A more complete example can be found here.

可以在此处找到更完整的示例。

回答by Han

Contributing a clean version that's easier to copy and paste.

提供一个更易于复制和粘贴的干净版本。

try {
    final URL url = new URL("http://your/url");
    HttpURLConnection huc = (HttpURLConnection) url.openConnection();
    int responseCode = huc.getResponseCode();
    // Handle response code here...
} catch (UnknownHostException uhe) {
    // Handle exceptions as necessary
} catch (FileNotFoundException fnfe) {
    // Handle exceptions as necessary
} catch (Exception e) {
    // Handle exceptions as necessary
}