new File(path).toURI().toURL();
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 🤷
java.nio.file.Paths
. Also, please be sure to make clear that you mean the implementations in "URI vs URL". Anway java.net.URL.toString()
produces the same thing on Unix, as it must. It only displays one "/" which is very wrong (see file URI scheme). I guess this is in Java because of reasons, better use java.net.URI
. It correctly generates "file://[host]/" on a call to .toString()
.
new File("path_to_file").toURI().toURL();
new URL("file:///your/file/here")
/your/file/here
is an absolute path to a file on Unix/Linux. On Windows it would be different I think.
new URL("file:my.properties");
file:///C:\\file.zip
File myFile=new File("/tmp/myfile");
URL myUrl = myFile.toURI().toURL();
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
File.toURI().toURL()
is the way to go
.properties
file.
java file url
, which in my case means that I was searching for the format of a file://
URL, in Java, for use in a .properties
file, or to type in manually, etc.
file://
is unfortunately necessary. Being system dependent is not such a huge issue since it's a mutable property.
You can also use
[AnyClass].class.getResource(filePath)
jar:file:/home/user/a/b/c/foo.jar!/com/example/stuff/config.txt
.
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
Success story sharing