4

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mihai8
  • 3,113
  • 1
  • 21
  • 31
  • Possible duplicate of [java.nio.file.Path for URLs?](https://stackoverflow.com/questions/8783523/java-nio-file-path-for-urls) – Justin Albano Jan 04 '19 at 14:16
  • No. Only `file:` URLs represent files on the host system. Are you sure you need a File? You can read from a URL with its [openStream](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/URL.html#openStream()) method. – VGR Jan 04 '19 at 15:03

2 Answers2

2

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);
Daniel B.
  • 2,491
  • 2
  • 12
  • 23
2

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

URL url = new URL(urlString);
File file = Paths.get(url.toURI().getPath()).toFile();
Loic Lacomme
  • 327
  • 3
  • 5