我的项目结构如下:
project/
- app/
- test/
- java/
- Utils.java
- resources/
- file.json
- BUILD.bazel
- BUILD.bazel我试图将file.json作为一个File对象加载,以便使用它来测试某些类。在Utils.java中,我试图将其解读为:
public class Utils {
public static File getSnapshotTestData() {
File file = new File(Utils.class.getClassLoader().getResource("file.json").getFile());
// Added this part to test the file was loaded correctly
try {
String data = FileUtils.readFileToString(file, "UTF-8"); // throws FileNotFound Exception
System.out.println("Data: " + data);
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
}即使file.getAbsolutePath()返回像/scratch/xxxx/.bazel/output/d03a9523f165711d724c4ed2c7f8d270/execroot/__main__/bazel-out/k8-opt/bin...这样的路径,如果我试图读取文件,也会得到FileNotFound。
知道这里可能出了什么问题吗?
在我的bazel文件中添加了以下内容:
project/BUILD.bazel
ARCHIVES = [
"//xxx/xxx/app/src/test/resources:file.json",
]
java_junit5_test(
name = "snapshot_admin_app_test",
srcs = glob(["src/test/java/**/*.java"]),
resources = glob(["src/test/resources/**/*.*"]) + ARCHIVES,
test_package = "com.xxx.xxx",
deps = DEPS + TESTING_DEPS,
)project/test/resources/BUILD.bazel
exports_files(["file.json"])发布于 2021-10-15 20:28:32
您需要将其包含在data属性中:
java_junit5_test(
name = "snapshot_admin_app_test",
srcs = glob(["src/test/java/**/*.java"]),
resources = glob(["src/test/resources/**/*.*"]) + ARCHIVES,
data = glob(["src/test/resources/**/*.*"]),
test_package = "com.xxx.xxx",
deps = DEPS + TESTING_DEPS,
)发布于 2022-04-16 21:38:29
我在从src/main/resources文件夹加载资源文件时也遇到了类似的问题。下面是Bazel松弛频道的答案:
当您在java目标上使用bazel时,所有资源文件都将被构建到与其java_library目标相对应的jars中,这意味着您不能直接在它们上使用getFile。尝试getResourceAsStream如果文件在数据param中,当您使用bazel时,它们将在$PWD上可用,但是它们不会内置到deploy中,它们也不会在类路径上
使用getResourceAsStream对我起了作用
https://stackoverflow.com/questions/69192209
复制相似问题