简体   繁体   English

使用 src/test/resources 作为 gradle java 的目录

[英]Use src/test/resources as directory with gradle java

I have got two working directories containing java code and resources, one is for testing and the other one is production.我有两个包含 java 代码和资源的工作目录,一个用于测试,另一个用于生产。

src/main/java源代码/主/Java
src/main/resources源代码/主要/资源

src/test/java源代码/测试/Java
src/test/resources源代码/测试/资源

When running my code and reading a file from FileInputStream like this:当运行我的代码并从 FileInputStream 读取文件时,如下所示:

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?有没有办法将 gradle 中的 src/test/resources 声明为 FileInputStream 查找资源的主文件夹?

If i put my file like this it works fine.如果我把我的文件像这样它工作正常。

在此处输入图片说明

But when I put the file in src/test/java/resources like this但是当我像这样将文件放在 src/test/java/resources 中时

在此处输入图片说明

I get a fileNotFoundException.我收到一个 fileNotFoundException。

I need a way to add this directory to be scanned with gradle.我需要一种方法来添加此目录以使用 gradle 进行扫描。



Adding this to build.gradle still throws a fileNotFoundException.将此添加到 build.gradle 仍然会引发 fileNotFoundException。

sourceSets {
test {
    java {
        srcDirs = ['src/test/java']
    }
    resources {
        srcDirs = ['src/test/resources']
        }
    }
}

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:如果你使用java或者,因为你似乎正在构建一个命令行应用程序, application插件,一切都会为你设置开箱即用:

plugins {
    id 'application'
}

You can remove all your sourceSet configurations and just load the file like so:您可以删除所有sourceSet配置,然后像这样加载文件:

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.最好遵循 Slaw 在问题下的评论并通过Class#getResourceAsStream(String)定位文件 - 但这有点超出了您的问题。

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

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