在Java中将本地文件传入URL

我如何使用本地文件创建一个新的URL对象,用于单元测试?

308334 次浏览
new URL("file:///your/file/here")
new File("path_to_file").toURI().toURL();
new File(path).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 myFile=new File("/tmp/myfile");
URL myUrl = myFile.toURI().toURL();

You can also use

[AnyClass].class.getResource(filePath)

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 🤷

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