Gradle 为 Ubuntu 上的现有文件抛出 NoSuchFileException
Gradle throw NoSuchFileException for existing file on Ubuntu
我正在做一个小型 Gradle 项目,想在 Spock 测试中使用我的 Reader
class。当我开始测试时 Reader
class 抛出:
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 中的协议指定的提供程序中提取路径(file: 在你的情况下)。
但是当您为 String
参数调用 Path.of()
时,它假定它是真实路径(file:project_path/build/resources/test/test.txt例)。
我正在做一个小型 Gradle 项目,想在 Spock 测试中使用我的 Reader
class。当我开始测试时 Reader
class 抛出:
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 中的协议指定的提供程序中提取路径(file: 在你的情况下)。
但是当您为 String
参数调用 Path.of()
时,它假定它是真实路径(file:project_path/build/resources/test/test.txt例)。