简体   繁体   English

Java 文件存在于 URL

[英]Java file exists at URL

Does anybody know a reliable method for seeing if a file exists at a URL, in Java?有没有人知道在 Java 中查看文件是否存在于 URL 的可靠方法?

Trying to see if the file exists before it is downloaded.在下载文件之前尝试查看文件是否存在。

(HTTP, btw.) (HTTP,顺便说一句。)


URL url = new URL ( some_url );
URLConnection connection = url.openConnection();

connection.connect();

// Cast to a HttpURLConnection
if ( connection instanceof HttpURLConnection)
{
   HttpURLConnection httpConnection = (HttpURLConnection) connection;

   int code = httpConnection.getResponseCode();

   // do something with code .....
}
else
{
   System.err.println ("error - not a http request!");
}

Usually HTTP error codes of 2xx represent success and 3xx for moved/redirection . Usually HTTP error codes of 2xx represent success and 3xx for moved/redirection

If you do get '3xx' errors, the response contains one or more header lines of the form URI: <url> String CrLf , use this new url and repeat above process.如果您确实收到 '3xx' 错误,则响应包含一个或多个格式为URI: <url> String CrLf标题行,使用这个新url并重复上述过程。

File exists URI with JAVA you can use :文件存在 URI 与 JAVA 您可以使用:

Files.exists(Paths.get(URI)) Files.exists(Paths.get(URI))

But that solution is not working with HTTP protocol (URL)但该解决方案不适用于 HTTP 协议 (URL)

instead, you can use the snippet below to verify file existence for http:// or file://相反,您可以使用下面的代码段来验证http://file:// 的文件是否存在

    try {
    InputStream openConnection = URI.create("https://your.domain.p1/path/1233/file.doc").toURL().openStream();
    } catch (Exception ex) {
        System.out.println(" invalid resource ");
    }

It isn't possible to do this generically.一般不可能做到这一点。 If you know that URL is a local url with a "file:" protocol, you can convert it into a regular File object and check its existence that way.如果您知道 URL 是带有“file:”协议的本地 url,则可以将其转换为常规 File 对象并以这种方式检查它的存在。 If the protocol is "http:", etc. you cannot check for existence without trying to open a stream.如果协议是“http:”等,你不能在不尝试打开流的情况下检查是否存在。 Even then you need to interpret the response (in protocol-dependent fashion) in order to know if something is there.即便如此,您也需要解释响应(以协议相关的方式)以了解是否存在某些内容。 For HTTP, you will probably get 404 response if file isn't found, but it could be another response code.对于 HTTP,如果找不到文件,您可能会收到 404 响应,但它可能是另一个响应代码。 Depends on the service you are accessing.取决于您访问的服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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