63

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.

1
  • 2
    Is this file being served through http? Commented Jan 4, 2011 at 17:19

6 Answers 6

103
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.

Source: http://www.rgagnon.com/javadetails/java-0059.html

Sign up to request clarification or add additional context in comments.

8 Comments

do we have to configure the lines mentioned in note (commented lines) ?
I wanna mention this: The server needs to be handling HEAD requests in order for this to work.
when I have a special char like 'Ü' in the filename, and parse it with URLEncoder.encode(filename, "UTF-8"), it tells me that the file does not exist?
This is a usefull link explaning HEAD method uses: ochronus.com/http-head-request-good-uses
@imdhmd But one should not disable the head request as explained here->security.stackexchange.com/questions/62811/…
|
16
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;
    }
  }  

Checking if a URL exists or not

Comments

6

Check this, it works for me. Source URL: Check if URL exists or not on Server

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     

    String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";

    MyTask task = new MyTask();
    task.execute(customURL);
}


private class MyTask extends AsyncTask<String, Void, Boolean> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Boolean doInBackground(String... params) {

         try {
                HttpURLConnection.setFollowRedirects(false);
                HttpURLConnection con =  (HttpURLConnection) new URL(params[0]).openConnection();
                con.setRequestMethod("HEAD");
                System.out.println(con.getResponseCode()); 
                return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
            }
            catch (Exception e) {   
                e.printStackTrace();    
                return false;
            }
    }

    @Override
    protected void onPostExecute(Boolean result) {
        boolean bResponse = result;
         if (bResponse==true)
            {
                Toast.makeText(MainActivity.this, "File exists!", Toast.LENGTH_SHORT).show();      
            }
            else
            {           
                Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
            }                  
    }           
}
}

1 Comment

This is Android related solution. OP didn't asked for Android solution.
4

Assuming the file is being served through http, you can send a HEAD request to the URL and check the http response code returned.

Comments

3

The only true way is to download it :). On some servers usually you can get away by issuing a HEAD request insted of a GET request for the same url. This will return you only the resource metadata and not the actual file content.

Update: Check org.life.java's answer for the actual technical details on how to do this.

Comments

0

Make a URLConnection to it. If you succeed, it exists. You may have to go so far as opening an input stream to it, but you don't have to read the contents. You can immediately close the stream.

1 Comment

InputStream implementations may not necessarily do a read on the server side so it may still not exist.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.