英文:
Use src/test/resources as directory with gradle java
问题
我有两个工作目录,包含了 Java 代码和资源文件,一个用于测试,另一个用于生产。
src/main/java
src/main/resources
src/test/java
src/test/resources
当我运行代码并从 FileInputStream 中读取文件时,像这样:
new FileInputStream("./someFile.json");
只要文件位于项目的根目录,这样就可以正常工作。如果我将文件放在资源文件夹中,并直接指向它,就像这样:
new FileInputStream("src/test/resources/someFile.json");
是否有一种方法在 Gradle 中声明 src/test/resources 作为 FileInputStream 查找资源的主文件夹?
如果我将我的文件放在这样的位置,它就可以正常工作。
但是,当我将文件放在 src/test/java/resources 中,就像这样:
我会得到一个 FileNotFoundException。
我需要一种方法将这个目录添加到 Gradle 的扫描范围中。
将下面的内容添加到 build.gradle 中仍然会抛出 FileNotFoundException。
sourceSets {
test {
java {
srcDirs = ['src/test/java']
}
resources {
srcDirs = ['src/test/resources']
}
}
}
英文:
I have got two working directories containing java code and resources, one is for testing and the other one is production.
src/main/java <br>
src/main/resources
src/test/java <br>
src/test/resources
When running my code and reading a file from FileInputStream like this:
new FileInputStream("./someFile.json");
As long a the file is located in the root of the project this works fine. It also works if I have the file in the resource folder and point directly to it like this:
new FileInputStream("src/test/resources/someFile.json");
Is there a way declaring src/test/resources in gradle as the main folder where FileInputStream looks for resources?
If i put my file like this it works fine.
But when I put the file in src/test/java/resources like this
I get a fileNotFoundException. <br>
I need a way to add this directory to be scanned with gradle.
<br><br>
Adding this to build.gradle still throws a fileNotFoundException.
sourceSets {
test {
java {
srcDirs = ['src/test/java']
}
resources {
srcDirs = ['src/test/resources']
}
}
}
答案1
得分: 4
如果您使用 java
或者,由于您似乎在构建命令行应用程序,使用 application
插件,一切都会为您预先设置好:
plugins {
id 'application'
}
您可以移除所有的 sourceSet
配置,然后像这样加载文件:
new FileInputStream("/someFile.json");
(注意,我写的是 /
而不是 ./
,这将把含义从“查找当前目录,项目根目录”更改为“查找类路径资源的根目录”)
根据Slaw在问题下的评论,最好是通过 Class#getResourceAsStream(String) 来定位文件 - 但这已经超出了您的问题范围。
英文:
If you use the java
or, since you seem to be building a command line application, the application
plugin, everything will be set up for you out of the box:
plugins {
id 'application'
}
You can remove all your sourceSet
configurations and just load the file like so:
new FileInputStream("/someFile.json");
(Notice that I wrote /
instead of ./
which changes the meaning from "look in the current directory, the project root" to "look in the root of a classpath resource".)
It would be even better to follow Slaw's comment under the question and locate the file via Class#getResourceAsStream(String) - but that's going beyond your question a bit.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论