首页 > 解决方案 > 当工作空间中存在文件时,Jenkins 抛出 NoSuchFileException

问题描述

我有一个方法调用,它读取并返回文件的内容,它在我的本地机器上运行良好 - Windows Server 2016,但是当它在我的 Jenkins 服务器上运行时 - 也存在于 Windows Server 机器上,它会抛出一个错误似乎找不到该文件,但我能够在 Jenkins 工作区中找到该文件,并在控制台中打印了确切的路径:

12:05:24 [Utils] [ERROR] [Error] java.nio.file.NoSuchFileException: C:\Users\****\AppData\Local\Jenkins\.jenkins\workspace\Maven%20Project%20Test\gems_automation\gems\GEMS\target\classes\getPM.sql
12:05:24    at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
12:05:24    at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
12:05:24    at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
12:05:24    at java.base/sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:235)
12:05:24    at java.base/java.nio.file.Files.newByteChannel(Files.java:371)
12:05:24    at java.base/java.nio.file.Files.newByteChannel(Files.java:422)
12:05:24    at java.base/java.nio.file.Files.readAllBytes(Files.java:3206)
12:05:24    at com.gems.testsuite.base.TestBaseUtils.readResourceFile(TestBaseUtils.java:23)

导致问题的方法是这样的:

public String  readResourceFile(String fileName) throws IOException {
        ClassLoader classLoader = getClass().getClassLoader();
        URL resource = classLoader.getResource(fileName);
        if (resource == null) {
            throw new IllegalArgumentException("file is not found!");
        } else {
            File file = new File(resource.getFile());
            Path path = Paths.get(FilenameUtils.separatorsToSystem(file.getPath()));
            return new String((Files.readAllBytes(path)));
        }
    }

我的本地和 Jenkins 也都使用相同的 maven 命令执行。

标签: javajenkinsnosuchfileexception

解决方案


我弄清楚了这个问题。

我的 Jenkins 项目名称有空格,因此当代码查找路径时,由于空格已被 ASCI 编码“%20”替换,因此无法找到它。最简单的解决方案是更改我的项目名称并排除空格。如果我真的想这样做,我可以用引号将整个路径包裹起来,这可能也可以。


推荐阅读