将本地文件传递到Java中的URL

Mea*_*ell 164 java url junit

URL为了进行单元测试,如何使用本地文件创建新对象?

jar*_*bjo 268

new File(path).toURI().toURL();
Run Code Online (Sandbox Code Playgroud)

  • 对于java 7+:Paths.get("path","to","stuff").toUri().toURL() (17认同)

Ted*_*opp 37

new File("path_to_file").toURI().toURL();
Run Code Online (Sandbox Code Playgroud)


Ale*_*sky 36

使用Java 7:

Paths.get(string).toUri().toURL();
Run Code Online (Sandbox Code Playgroud)

但是,你可能想得到一个URI.例如,a URI开头file:///只有一个URL file:/(至少是toString产生的东西).

  • 不是.URL只是URI的特例.文件URI以"file://"开头,然后列出主机(通常省略),后跟"/"和路径"foo/bar"(通常意味着作为绝对路径读取).因此"file:/// foo/var".看起来像"file:/ foo/bar"的URI不正确.另请参阅:[文件URI方案](https://en.wikipedia.org/wiki/File_URI_scheme) (5认同)
  • @AleksandrDubinsky尽管如此,最好留下指向Oracle javadoc的指针..更容易点击进入`java.nio.file.Paths`.此外,请务必明确指出"URI vs URL"中的_implementations_.Anway`java.net.URL.toString()`在Unix上生成相同的东西,因为它必须.它只显示一个"/",这是_very wrong_(参见[文件URI方案](https://en.wikipedia.org/wiki/File_URI_scheme)).我想这是因为Java的原因,更好地使用`java.net.URI`.它在调用`.toString()`时正确生成"file:// [host] /". (3认同)

Ale*_*lex 20

new URL("file:///your/file/here")
Run Code Online (Sandbox Code Playgroud)

  • 这不是很聪明,因为你必须自己处理URL中不允许的字符转义.在Windows(以及可能的其他操作系统)上,还必须修改从文件的本机路径的路径分隔符. (5认同)
  • 在 Windows 上,以下内容对我有用:`file:///C:\\file.zip` (2认同)

Sea*_*oyd 9

File myFile=new File("/tmp/myfile");
URL myUrl = myFile.toURI().toURL();
Run Code Online (Sandbox Code Playgroud)


Liv*_*Liv 5

有关完整的语法,请看这里:http : //en.wikipedia.org/wiki/File_URI_scheme( 对于类似Unix的系统)将像@Alex所说的,file:///your/file/here而对于Windows系统将file:///c|/path/to/file

  • 不要手动做。File.toURI()。toURL()是解决方法 (7认同)
  • @SeanPatrickFloyd有时您别无选择,例如当它位于`.properties`文件中时。 (3认同)
  • @SeanPatrickFloyd,当您搜索`java file url`时出现此问题/答案,在我的情况下,这意味着我正在搜索Java中`file://`URL的格式,以用于`中。属性文件,或手动输入等等。 (2认同)