Pass a local file in to URL in Java

JavaUrlJunit

Java Problem Overview


How do I create a new URL object using a local file, for the purpose of unit tests?

Java Solutions


Solution 1 - Java

new File(path).toURI().toURL();

Solution 2 - Java

Using Java 11:

Path.of(string).toUri();

Using Java 7:

Paths.get(string).toUri();

To convert to the old-school URL class (why?), add .toURL(). Note there is a difference in the string output. The modern URI::toString begins with file:/// (the traditional URL syntax) while the nearly-deprecated URL::toString with file:/ (the modern URI syntax). Weird 路

Solution 3 - Java

new File("path_to_file").toURI().toURL();

Solution 4 - Java

new URL("file:///your/file/here")

Solution 5 - Java

File myFile=new File("/tmp/myfile");
URL myUrl = myFile.toURI().toURL();

Solution 6 - Java

have a look here for the full syntax: http://en.wikipedia.org/wiki/File_URI_scheme for unix-like systems it will be as @Alex said file:///your/file/here whereas for Windows systems would be file:///c|/path/to/file

Solution 7 - Java

You can also use

[AnyClass].class.getResource(filePath)

Solution 8 - Java

I tried it with Java on Linux. The following possibilities are OK:

file:///home/userId/aaaa.html
file:/home/userId/aaaa.html
file:aaaa.html  (if current directory is /home/userId)

not working is:

file://aaaa.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMeanwhileInHellView Question on Stackoverflow
Solution 1 - JavajarnbjoView Answer on Stackoverflow
Solution 2 - JavaAleksandr DubinskyView Answer on Stackoverflow
Solution 3 - JavaTed HoppView Answer on Stackoverflow
Solution 4 - JavaAlexView Answer on Stackoverflow
Solution 5 - JavaSean Patrick FloydView Answer on Stackoverflow
Solution 6 - JavaLivView Answer on Stackoverflow
Solution 7 - JavaxMichalView Answer on Stackoverflow
Solution 8 - JavaSzBView Answer on Stackoverflow