URL 处存在 Java 文件
有谁知道在 Java 中查看 URL 中是否存在文件的可靠方法吗?
尝试在下载文件之前查看该文件是否存在。
(顺便说一句,HTTP。)
Does anybody know a reliable method for seeing if a file exists at a URL, in Java?
Trying to see if the file exists before it is downloaded.
(HTTP, btw.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般情况下不可能做到这一点。如果您知道 URL 是带有“file:”协议的本地 url,则可以将其转换为常规 File 对象并以这种方式检查其是否存在。如果协议是“http:”等,则在不尝试打开流的情况下无法检查其存在。即使这样,您也需要解释响应(以依赖于协议的方式),以便知道是否存在某些内容。对于 HTTP,如果未找到文件,您可能会收到 404 响应,但它可能是另一个响应代码。取决于您正在访问的服务。
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. If the protocol is "http:", etc. you cannot check for existence without trying to open a stream. 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. Depends on the service you are accessing.
文件存在 JAVA URI,您可以使用:
Files.exists(Paths.get(URI))
但该解决方案不适用于 HTTP 协议 (URL)
,您可以使用下面的代码片段来验证文件http:// 或 file:// 的存在
File exists URI with JAVA you can use :
Files.exists(Paths.get(URI))
But that solution is not working with HTTP protocol (URL)
instead, you can use the snippet below to verify file existence for http:// or file://
通常 HTTP 错误代码 2xx 表示成功,3xx 表示移动/重定向
。如果您确实收到“3xx”错误,则响应包含一个或多个
URI:形式的标题行。 String CrLf
,使用这个新的url
并重复上述过程。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 newurl
and repeat above process.