gpt4 book ai didi

java - Gradle 对 Ubuntu 上的现有文件抛出 NoSuchFileException

转载 作者:行者123 更新时间:2023-11-30 05:46:30 26 4
gpt4 key购买 nike

我正在开发一个小型 Gradle 项目,并希望在 Spock 测试中使用我的 Reader 类。当我开始测试时,Reader 类抛出:

java.nio.file.NoSuchFileException

在我的 Gradle 项目中,我在 /src/test/resources 中有 test.txt 文件。当我使用 Reader 运行测试时,Gradle 会向我显示:

java.nio.file.NoSuchFileException: file:project_path/build/resources/test/test.txt

即使该路径中有一个文件。我使用终端和浏览器进行了检查。

我在 Ubuntu 上使用 Java 11。

//Reader class read lines:    
try (Stream<String> stream = Files.lines(Path.of(String.valueOf(getClass().getClassLoader().getResource(fileName)))))

//gradle.build without test dependencies
apply plugin: "java"
apply plugin: "groovy"

group = "com.example"
version = "1.0"
sourceCompatibility = "1.11"

repositories {
mavenCentral()
}

最佳答案

更改您的 Reader 读取逻辑:

try (Stream<String> stream = Files.lines(Path.of(ClassLoader.getSystemResource(fileName).toURI()))) {
...
}

Path.of() 将在使用 URI 时创建正确的路径:/project_path/build/resources/test/test.txt 因为它将从提供程序中提取路径由 URI 中的协议(protocol)指定(在您的情况下为文件:)。

但是当您为 String 参数调用 Path.of() 时,它假定它是真实路径(file:project_path/build/resources/test/test.txt 在你的情况下)。

关于java - Gradle 对 Ubuntu 上的现有文件抛出 NoSuchFileException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54737839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com