tags:

views:

96

answers:

1

http://stackoverflow.com/questions/1979915/can-i-check-if-a-file-exists-at-a-url

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

+4  A: 

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

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

A more complete example can be found here.

HTH, flokra

flokra
I just wanted to note that some websites will not actually return a 404 status code, but rather redirect to a custom error page (and return 200 Successful). This is bad behavior, but it is worth ensuring that the site you are testing against isn't serving up these "soft" 404s.
Kris
1) You may want to catch `UnknownHostException` and `FileNotFoundException` on `openConnection()` method (both just `IOException`). 2) You also want to cast the `URLConnection` down to `HttpURLConnection` to be able to call the `getResponseCode()` method. And @Kris: a redirect would result in a 301 or 302 which you need to handle at any way. The URL might for instance have been updated.
BalusC
Also if the file is quite large you'll end up downloading the entire content to check for existence. If you issue a HEAD request instead of a GET you'll get better mileage.
Raymond