问题描述
我有一个方法调用,它读取并返回一个文件的内容,它在我的本地机器上运行良好 - 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 命令执行。
解决方法
我发现了这个问题。
我的 Jenkins 项目名称有空格,所以当代码查找路径时,找不到它,因为空格被 ASCI 编码“%20”替换。最简单的解决方案是更改我的项目名称并排除空格。如果我真的想要,我可以用引号包裹整个路径,这可能也有效。