10

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.

Community
  • 1
  • 1
senzacionale
  • 20,448
  • 67
  • 204
  • 316

2 Answers2

12

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.

  • 2
    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 Mar 17 '10 at 12:37
  • 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 Mar 17 '10 at 12:56
  • 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 Kroeker Apr 11 '10 at 18:34
5

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
}
Han
  • 5,374
  • 5
  • 31
  • 31