如何从资源文件夹加载文件?
我的项目具有以下结构:
/src/main/java/
/src/main/resources/
/src/test/java/
/src/test/resources/
我在/src/test/resources/test.csv
中有一个文件,我想从/src/test/java中的单元测试中加载文件/mytest.java
我有此代码,该代码不起作用。它抱怨“没有这样的文件或目录”。
BufferedReader br = new BufferedReader (new FileReader(test.csv))
我也尝试过
InputStream is = (InputStream) MyTest.class.getResourcesAsStream(test.csv))
这也行不通。它返回 null
。我正在使用Maven来构建我的项目。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(26)
尝试下一个:
如果以上不起作用,则添加了以下类别的各个项目:
classLoaderutil
1 (代码在这里)。 2这是一些如何使用该类的示例:
notes
Try the next:
If the above doesn't work, various projects have been added the following class:
ClassLoaderUtil
1 (code here).2Here are some examples of how that class is used:
Notes
尝试:
IIRC
getResourceasStream()
默认情况下是相对于类的软件包。正如@terran所指出的,不要忘记在文件名开始时添加
/
Try:
IIRC
getResourceAsStream()
by default is relative to the class's package.As @Terran noted, don't forget to add the
/
at the starting of the filename尝试遵循春季项目
或非春季项目上的代码
Try following codes on Spring project
Or on non spring project
这是一个快速解决方案,使用 guava :
用法:
Here is one quick solution with the use of Guava:
Usage:
非春季项目:
或者
对于春季项目,您还可以使用一个行代码在Resources文件夹下获取任何文件:
Non spring project:
Or
For spring projects, you can also use one line code to get any file under resources folder:
对于Java 1.7
另外,如果您在Spring Echosystem中可以使用Spring Utils,可以使用Spring
Utils,以了解更多现场,请在博客
https://todzhang.com/blogs/tech/en/save_resources_to_files
For java after 1.7
Alternatively you can use Spring utils if you are in Spring echosystem
To get to more behind the scene, check out following blog
https://todzhang.com/blogs/tech/en/save_resources_to_files
我面对同一问题。
该文件是由类加载程序找到的,这意味着它没有包装到工件中(JAR)。您需要构建项目。例如,使用Maven:
因此,您添加到Resources文件夹的文件将进入Maven构建,并可用于应用程序。
我想保持答案:它没有解释如何读取文件(其他答案确实解释了),它回答为什么
inputStream
或资源>代码>是 null 。类似答案在这里。
I faced the same issue.
The file was not found by a class loader, which means it was not packed into the artifact (jar). You need to build the project. For example, with maven:
So the files you added to resources folder will get into maven build and become available to the application.
I would like to keep my answer: it does not explain how to read a file (other answers do explain that), it answers why
InputStream
orresource
was null. Similar answer is here.如果您使用上下文classloader查找资源,那么它肯定会花费应用程序性能。
If you use context ClassLoader to find a resource then definitely it will cost application performance.
现在,我说明了读取Maven创建资源目录的字体的源代码,
你,享受!
Now I am illustrating the source code for reading a font from maven created resources directory,
It worked for me and hope that the entire source code will also help you, Enjoy!
导入以下内容:
以下方法返回字符串阵列列表中的文件:
Import the following:
The following method returns a file in an ArrayList of Strings:
您可以使用com.google.common.io.resources.getResource读取文件的URL,然后使用java.nio.file.files获取文件内容以读取文件的内容。
You can use the com.google.common.io.Resources.getResource to read the url of file and then get the file content using java.nio.file.Files to read the content of file.
如果要以静态方法加载文件,则
classloader classloader = getClass()。getClassloader();
这可能会给您带来错误。
你可以尝试这个
例如,您要从资源加载的文件是资源>>图像>> test.gif
if you are loading file in static method then
ClassLoader classLoader = getClass().getClassLoader();
this might give you an error.
You can try this
e.g. file you want to load from resources is resources >> Images >> Test.gif
GetResource()仅在
src/main/resources
中放置的资源文件工作正常。要获取src/main/resources
Saysrc/test/java
以外的路径上的文件,您需要先于固定地创建它。以下示例可能会帮助您
getResource() was working fine with the resources files placed in
src/main/resources
only. To get a file which is at the path other thansrc/main/resources
saysrc/test/java
you need to create it exlicitly.the following example may help you
要从SRC/Resources文件夹中读取文件,然后尝试以下操作:
如果没有静态参考:
To read the files from src/resources folder then try this :
in case of non static reference:
对于Kotlin,我正在做以下操作:
(对于Android Studio,转到文件 - > new-> folder - > Assets文件夹)
导入这些项目:
我创建了这样的函数:这样:
For Kotlin I am doing the following:
(for Android studio go to File -> New-> Folder -> Assets Folder)
Import these items:
I created a function like this:
例如,从IDE运行时,该代码在不运行maven-build jar时是否有效?如果是这样,请确保文件实际上包含在JAR中。资源文件夹应包含在
<构建中的POM文件中。
Does the code work when not running the Maven-build jar, for example when running from your IDE? If so, make sure the file is actually included in the jar. The resources folder should be included in the pom file, in
<build><resources>
.以下类可用于从
classPath
中加载资源
,并且还会收到一条拟合错误消息,以防给定filepath
有问题。 。The following class can be used to load a
resource
from theclasspath
and also receive a fitting error message in case there's a problem with the givenfilePath
.即使我遵循答案,也找不到我在测试文件夹中的文件。它通过重建项目来解决。似乎Intellij并未自动识别新文件。很讨厌找出答案。
My file in the test folder could not be found even though I followed the answers. It got resolved by rebuilding the project. It seems IntelliJ did not recognize the new file automatically. Pretty nasty to find out.
我通过写作作为在运行罐子和IDE上的工作
I got it work on both running jar and in IDE by writing as
我目前正在这样做。
这是我的结构。
我正在与Java 11一起工作。
I am currently doing it this way.
This is my structure.

I am working with Java 11.
对于Kotlin:
For Kotlin:
如果要获取文件对象:
If you want to get a File object:
从资源文件夹中加载文件作为流,
以便在资源文件夹中访问文件,您应该使用方法
无论您的应用程序正在开发,测试还是构建,这种方法都可以访问资源。实际上,当使用Maven或Gradle等构建工具时,将资源从
../ src/main/resources
复制到target/class/class
或构建的根部/类
。基本上,getResourCeasStream()
方法以独立于代码的位置的方式授予您通过类代码访问资源。从资源文件夹中加载文件java.io.file
或者,如果您需要一个
java.io.file
,您可以使用 方法将资源检索为url
,并创建一个文件
来自资源路径或URI。但是,使用URI需要处理urisyntaxexception
。从资源文件夹加载文件java.nio.file.path
,如果您需要一个
java.nio.file.path
,您可以使用静态方法path.of()
(来自JDK 11)带有资源URI的路径
。Load File from Resource Folder as Stream
To generically access a file in a resource folder, you should use the method
getResourceAsStream()
.This approach allows you to access a resource whether your application is being developed, tested or built. In fact, when using build tools like Maven or Gradle, resources are copied from
../src/main/resources
to the root oftarget/classes
orbuild/classes
. Basically, thegetResourceAsStream()
method grants you to access a resource by class code in a way that is independent of the location of the code.Load File from Resource Folder as java.io.File
Alternatively, if you need an instance of
java.io.File
, you can employ thegetResource()
method to retrieve the resource as aURL
, and create aFile
from the resource's path or URI. However, using the URI requires handling theURISyntaxException
.Load File from Resource Folder as java.nio.file.Path
Instead, if you need an instance of
java.nio.file.Path
, you can employ the static methodPath.of()
(from JDK 11) to build aPath
with the resource's URI.这对我来说很好:
This worked pretty fine for me :
我可以将其工作起作用,而无需提及“类”或“ ClassLoader”。
假设我们有三种情况,即文件“示例”的位置,您的工作目录(您的应用程序执行)是Home/myDocuments/program/projection/myapp:
a)工作目录的子文件夹后代:
myApp/res/files/xplove.file
b)一个非后代的子文件夹:工作目录:
projects/files/example.file
b2)另一个子文件夹不是工作目录的后代:
程序/文件/示例。文件
c)根文件夹:
home/mydocuments/files/example.file(linux;在Windows中替换为Home/c :)
1)获取正确的路径:
a)
字符串路径=“ res/files/example.file”;
b)
字符串路径=“ ../ projects/files/example.file”
b2)
字符串路径=“ ../../ program/files/example.file”
c)
字符串路径=“/home/mydocuments/files/example.file”
基本上,如果它是根文件夹,请使用领先的斜杠启动路径名。
如果是子文件夹,则不得在路径名之前进行斜杠。如果子文件夹不是工作目录的后代,则必须使用“ ../”来cd。这告诉系统上一个文件夹。
2)通过传递正确的路径来创建文件对象:
3)您现在很好:
I get it to work without any reference to "class" or "ClassLoader".
Let's say we have three scenarios with the location of the file 'example.file' and your working directory (where your app executes) is home/mydocuments/program/projects/myapp:
a)A sub folder descendant to the working directory:
myapp/res/files/example.file
b)A sub folder not descendant to the working directory:
projects/files/example.file
b2)Another sub folder not descendant to the working directory:
program/files/example.file
c)A root folder:
home/mydocuments/files/example.file (Linux; in Windows replace home/ with C:)
1) Get the right path:
a)
String path = "res/files/example.file";
b)
String path = "../projects/files/example.file"
b2)
String path = "../../program/files/example.file"
c)
String path = "/home/mydocuments/files/example.file"
Basically, if it is a root folder, start the path name with a leading slash.
If it is a sub folder, no slash must be before the path name. If the sub folder is not descendant to the working directory you have to cd to it using "../". This tells the system to go up one folder.
2) Create a File object by passing the right path:
3) You are now good to go: