Pass a local file in to URL in Java
JavaUrlJunitJava 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