0

I wanted to write sample code which will connect to remote server and check if the given file exist on that server. I have IP address, username, password and port. Is there any way I can check if the file exist on remote server? I know this can be done using third party library. But I am looking using java APi's Could you please help me?

Sachin
  • 247
  • 4
  • 16
  • 26

1 Answers1

-1

Check this question in Stack Overflow: Check if file exists on remote server using its URL

It has an answer to your question:

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.

Community
  • 1
  • 1
Armine
  • 1,675
  • 2
  • 24
  • 40