Does anybody know a reliable method for seeing if a file exists at a URL, in Java?
开发者_如何学PythonTrying to see if the file exists before it is downloaded.
(HTTP, btw.)
URL url = new URL ( some_url );
URLConnection connection = url.openConnection();
connection.connect();
// Cast to a HttpURLConnection
if ( connection instanceof HttpURLConnection)
{
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int code = httpConnection.getResponseCode();
// do something with code .....
}
else
{
System.err.println ("error - not a http request!");
}
Usually HTTP error codes of 2xx represent success and 3xx for moved/redirection
.
If you do get '3xx' errors, the response contains one or more header lines of the form URI: <url> String CrLf
, use this new url
and repeat above process.
File exists URI with JAVA you can use :
Files.exists(Paths.get(URI))
But that solution is not working with HTTP protocol (URL)
instead, you can use the snippet below to verify file existence for http:// or file://
try {
InputStream openConnection = URI.create("https://your.domain.p1/path/1233/file.doc").toURL().openStream();
} catch (Exception ex) {
System.out.println(" invalid resource ");
}
It isn't possible to do this generically. If you know that URL is a local url with a "file:" protocol, you can convert it into a regular File object and check its existence that way. If the protocol is "http:", etc. you cannot check for existence without trying to open a stream. Even then you need to interpret the response (in protocol-dependent fashion) in order to know if something is there. For HTTP, you will probably get 404 response if file isn't found, but it could be another response code. Depends on the service you are accessing.
精彩评论