[英]Can't get to a file located under src/main/resources/
I am trying to get to a file located under resources and get null
: 我正在尝试访问位于资源下的文件并获取
null
:
File propertiesFile = new File(this.getClass().getClassLoader().getResource(file).getFile());
file = Log.csv
Even if the file is directly under resource or under one of the folders under it. 即使文件直接在资源下或在其下的文件夹之一下。
this.getClass().getClassLoader().getResource(file)
- return null
this.getClass().getClassLoader().getResource(file)
-返回null
this.getClass().getClassLoader().getResource(file).getFile()
capture the path till resources
folder, if you have folder inside resources
then you have to give that along with the file name. 捕获直到
resources
文件夹的路径,如果您在resources
内部有文件夹,则必须提供该路径以及文件名。
for example - 例如 -
resources -> folder -> test.csv
Then give file name : 然后给文件名:
String file = "folder/test.csv";
Hope this helps! 希望这可以帮助!
Resources are not real File
s on the file system, but on the class path . 资源不是文件系统上的实际
File
,而是类路径上的 。 They could be packed in a jar with an URL like "jar:file://.../xyz.jar!test.csv"
. 可以将它们包装在具有URL的jar中,例如
"jar:file://.../xyz.jar!test.csv"
。 Hence use an InputStream. 因此,使用InputStream。
InputStream in = getClass().getResourceAsStream("/test.csv");
String userHome = System.getProperty("user.home");
Path path = Paths.get(userHome, "test2.csv");
Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);
Resources should be considered read-only ; 资源应被视为只读 ; hence use them as template, initial empty file, read-only data or such.
因此,请将它们用作模板,初始空文件,只读数据等。
The ClassLoader has only absolute paths under the root src/main/resources, without starting /
. ClassLoader在根src / main / resources下只有绝对路径,而没有以
/
开头。 The Class has URLs relative to the class' package directory (but under src/main/resources), or starting with /
an absolute path. 类具有相对于类的包目录的URL(但在src / main / resources下),或者以
/
绝对路径开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.