[英]File object from URL with http or https
可以从URL获取File对象吗? 我尝试类似的东西
URL url = new URL(urlString);
File file = Paths.get(url.toURI()).toFile();
但它获得了例外
java.nio.file.FileSystemNotFoundException: Provider "http" not installed
或https ...取决于所使用的协议。 假设urlString包含有效地址。
是否存在一种从URL获取File对象的替代方法,或者我使用的是错误的方法?
您需要打开与URL的连接,开始获取服务器发送给您的字节,并将其保存到文件中。
URL website = new URL("http://www.website.com/information.asp");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("information.html");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
另一种方法是使用apache common io库,您可以这样做:
URL url = new URL(urlString);
File file = new File("filename.html");
FileUtils.copyURLToFile(url, file);
尝试在将其传递给Paths.get()之前使用URI.getPath()
URL url = new URL(urlString);
File file = Paths.get(url.toURI().getPath()).toFile();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.