Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File object from URL with http or https

Tags:

java

file

url

Can be obtain a File object from URL? I try something like

URL url = new URL(urlString);
File file = Paths.get(url.toURI()).toFile();

but it obtained exception

java.nio.file.FileSystemNotFoundException: Provider "http" not installed

or https... depending on the protocol used. Assume that urlString contain a valid address.

Exist an altenative to get it the File object from URL or I'm on wrong way?

like image 522
Mihai8 Avatar asked Nov 02 '25 09:11

Mihai8


2 Answers

You need to open a connection to the URL, start getting the bytes the server is sending you, and save them to a file.

Using Java NIO

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);

Using Apache Common IO

Another approach is to use the apache common io library, and you can do it like this:

URL url = new URL(urlString);
File file = new File("filename.html");
FileUtils.copyURLToFile(url, file);
like image 188
Daniel B. Avatar answered Nov 03 '25 22:11

Daniel B.


Try to use URI.getPath() before passing it to Paths.get()

URL url = new URL(urlString);
File file = Paths.get(url.toURI().getPath()).toFile();
like image 29
Loic Lacomme Avatar answered Nov 03 '25 22:11

Loic Lacomme