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

时间:2023-02-12 05:06:21

How do I create a new URL object using a local file, for the purpose of unit tests?

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

7 个解决方案

#1


232  

new File(path).toURI().toURL();

#2


34  

new File("path_to_file").toURI().toURL();

#3


25  

Using Java 7:

使用Java 7:

Paths.get(string).toUri().toURL();

However, you probably want to get a URI. Eg, a URI begins with file:/// but a URL with file:/ (at least, that's what toString produces).

但是,您可能希望得到一个URI。URI以文件开头:///但有一个带文件的URL:/(至少,这就是toString所产生的)。

#4


19  

new URL("file:///your/file/here")

#5


8  

File myFile=new File("/tmp/myfile");
URL myUrl = myFile.toURI().toURL();

#6


3  

You can also use

您还可以使用

[AnyClass].class.getResource(filePath)

#7


2  

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

这里有一个完整的语法:http://en.wikipedia.org/wiki/File_URI_scheme,用于类unix系统,它将像@Alex所说的文件:/// //这里,而Windows系统将是文件:///c|/路径/文件?

#1


232  

new File(path).toURI().toURL();

#2


34  

new File("path_to_file").toURI().toURL();

#3


25  

Using Java 7:

使用Java 7:

Paths.get(string).toUri().toURL();

However, you probably want to get a URI. Eg, a URI begins with file:/// but a URL with file:/ (at least, that's what toString produces).

但是,您可能希望得到一个URI。URI以文件开头:///但有一个带文件的URL:/(至少,这就是toString所产生的)。

#4


19  

new URL("file:///your/file/here")

#5


8  

File myFile=new File("/tmp/myfile");
URL myUrl = myFile.toURI().toURL();

#6


3  

You can also use

您还可以使用

[AnyClass].class.getResource(filePath)

#7


2  

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

这里有一个完整的语法:http://en.wikipedia.org/wiki/File_URI_scheme,用于类unix系统,它将像@Alex所说的文件:/// //这里,而Windows系统将是文件:///c|/路径/文件?