简体   繁体   English

实例化java.io.File以从类路径中读取资源

[英]Instancing a java.io.File to read a resource from classpath

Supposing that I've a project structure as follows: 假设我的项目结构如下:

+ src
---+ main
------+ java
------+ resources

How can I define a java.io.File instance that is able to read an xml from resources folder? 如何定义一个能够从资源文件夹读取xml的java.io.File实例?

It depends on what your program's working directory is. 这取决于程序的工作目录。

You can get your working directory at runtime via System.getProperty("user.dir"); 您可以在运行时通过System.getProperty("user.dir");获得工作目录System.getProperty("user.dir");

Here's a link with more info 这是更多信息的链接

Once you've got that, create a relative filepath pointing to your resource folder. 一旦知道了,创建一个指向您的资源文件夹的相对文件路径。

For example, if your working directory is src, create a relative filepath like so: 例如,如果您的工作目录是src,则创建一个相对文件路径,如下所示:

new File(Paths.get("main","resources").toString());

There are weaknesses with this approach as the actual filepath you use may change when you deploy your application, but it should get you through some simple development. 这种方法有一些缺点,因为在部署应用程序时,您使用的实际文件路径可能会更改,但是它应该可以帮助您完成一些简单的开发。

No, use an InputStream, with the path starting under resources. 不,使用InputStream,路径从资源下开始。

InputStream in = getClass().getResourceAsStrem("/.../...");

Or an URL 或网址

URL url = getClass().getResource("/.../...");

This way, if the application is packed in a jar (case sensitive names!) it works too. 这样,如果应用程序打包在jar中(区分大小写的名称!),它也可以工作。 The URL in that case is: 在这种情况下,URL为:

"jar:file://... .jar!/.../..."

If you need the resource as file, for instance to write to, you will need to copy the resource as initial template to some directory outside the application, like System.getProperty("user.home") . 例如,如果需要将资源作为文件写入,则需要将资源作为初始模板复制到应用程序之外的某个目录,例如System.getProperty("user.home")

Path temp = Files.createTempFile("pref", "suffix.dat");
Files.copy(getClass().getResourceAsStream(...), temp, StandardCopyOption.REPLACE_EXISTING);
File file = temp.toFile();

As @mjaggard commented, createTempFile creates an empty file, so Files.copy will normally fail unless with option REPLACE_EXISTING. 作为@mjaggard评论, createTempFile创建一个空文件,所以Files.copy通常会失败,除非使用选项REPLACE_EXISTING。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM