Kar*_*l S 148
实际工作的正确方法:
URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();
Run Code Online (Sandbox Code Playgroud)
现在,类路径中的文件在物理上的位置并不重要,只要资源实际上是文件而不是JAR条目,就会找到它.
(看似明显new File(resource.getPath())不适用于所有路径!路径仍然是URL编码的!)
Rah*_*ate 41
您可以使用ClassLoader.getResource方法来获取正确的资源.
URL res = getClass().getClassLoader().getResource("abc.txt");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();
Run Code Online (Sandbox Code Playgroud)
要么
虽然这可能不会一直有效,但更简单的解决方案 -
您可以创建一个File对象并使用getAbsolutePath方法:
File file = new File("resources/abc.txt");
String absolutePath = file.getAbsolutePath();
Run Code Online (Sandbox Code Playgroud)
Het*_*ett 21
您必须指定从中开始的路径 /
URL resource = YourClass.class.getResource("/abc");
Paths.get(resource.toURI()).toFile();
Run Code Online (Sandbox Code Playgroud)
小智 11
创建所需类的classLoader实例,然后您可以轻松地访问文件或资源.现在您使用getPath()该类的方法访问路径.
ClassLoader classLoader = getClass().getClassLoader();
String path = classLoader.getResource("chromedriver.exe").getPath();
System.out.println(path);
Run Code Online (Sandbox Code Playgroud)
There are two problems on our way to the absolute path:
The following code will give us all useful paths:
URL localPackage = this.getClass().getResource("");
URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation();
String localDir = localPackage.getPath();
String loaderDir = urlLoader.getPath();
System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir);
Run Code Online (Sandbox Code Playgroud)
Here both functions that can be used for localization of the resource folder are researched. As for class, it can be got in either way, statically or dynamically.
If the project is not in the plugin, the code if run in JUnit, will print:
loaderDir = /C:.../ws/source.dir/target/test-classes/
localDir = /C:.../ws/source.dir/target/test-classes/package/
Run Code Online (Sandbox Code Playgroud)
因此,要到达 src/rest/resources,我们应该在文件树中上下移动。两种方法都可以使用。请注意,我们不能使用getResource(resourceFolderName),因为该文件夹不在目标文件夹中。我希望没有人将资源放入创建的文件夹中。
如果该类位于插件的包中,则相同测试的输出将是:
loaderDir = /C:.../ws/plugin/bin/
localDir = /C:.../ws/plugin/bin/package/
Run Code Online (Sandbox Code Playgroud)
因此,我们应该再次在文件夹树中上下移动。
最有趣的是在插件中启动包时的情况。作为 JUnit 插件测试,以我们为例。输出是:
loaderDir = /C:.../ws/plugin/
localDir = /package/
Run Code Online (Sandbox Code Playgroud)
这里我们只需结合两个函数的结果就可以得到绝对路径。但这还不够。在它们之间,我们应该放置类包所在位置的本地路径(相对于插件文件夹)。也许,您必须在此处插入一些内容 assrc或src/test/resource。
您可以将代码插入到您的代码中并查看您拥有的路径。
| 归档时间: |
|
| 查看次数: |
203665 次 |
| 最近记录: |