我是靠谱客的博主 迷人指甲油,这篇文章主要介绍java url 本地文件是否存在,使用URL检查远程服务器上是否存在文件,现在分享给大家,希望可以做个参考。

How can I check in Java if a file exists on a remote server (served by HTTP), having its URL? I don't want to download the file, just check its existence.

解决方案

import java.net.*;

import java.io.*;

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;

}

}

If the connection to a URL (made with HttpURLConnection) returns with HTTP status code 200 then the file exists.

EDIT: Note that since we only care it exists or not there is no need to request the entire document. We can just request the header using the HTTP HEAD request method to check if it exists.

最后

以上就是迷人指甲油最近收集整理的关于java url 本地文件是否存在,使用URL检查远程服务器上是否存在文件的全部内容,更多相关java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(119)

评论列表共有 0 条评论

立即
投稿
返回
顶部