简体   繁体   中英

check if file exist on remote server using Java code

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM