How do I create a new URL object using a local file, for the purpose of unit tests?
9 Answers
new File(path).toURI().toURL();
1 Comment
NIO.2 in modern Java
Java I/O improved dramatically with the arrival of NIO and NIO.2. See guide by Oracle. See Wikipedia.
Using Path.of in Java 11 and later:
Path.of(string).toUri();
Or in earlier Java use Paths.get.
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 🤷
6 Comments
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 URL("file:///your/file/here")
4 Comments
/your/file/here is an absolute path to a file on Unix/Linux. On Windows it would be different I think.file:///C:\\file.ziphave 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
5 Comments
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)
2 Comments
jar:file:/home/user/a/b/c/foo.jar!/com/example/stuff/config.txt.