【问题标题】:Gradle throw NoSuchFileException for existing file on UbuntuGradle 为 Ubuntu 上的现有文件抛出 NoSuchFileException
【发布时间】:2019-02-17 21:25:56
【问题描述】:

我正在开发一个小型 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()
}

【问题讨论】:

    标签: java unix gradle spock


    【解决方案1】:

    更改您的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 在您的情况下)。 p>

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      • 1970-01-01
      相关资源
      最近更新 更多