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?

2
  • Possible duplicate of java.nio.file.Path for URLs? Commented Jan 4, 2019 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 method. Commented Jan 4, 2019 at 15:03

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.