java - 使用 getClassLoader().getResource 时 Linux 机器上的 FileNotFoundException

标签 java linux

我已经在互联网上针对这个问题进行了相当多的研究。到目前为止我没有运气。基本上,这段代码在 Windows 上使用我的 Junit 测试 src\test\java\com\project\utils\MyTestCase.java 运行良好:

URL urlApplicationContext = this.getClass().getClassLoader().getResource("applicationContext.xml");
final String[] paths = { urlApplicationContext.getFile()};
ApplicationContext ctx = new FileSystemXmlApplicationContext(paths);

这个文件位于:

\src\test\resources\applicationContext.xml

但是在运行 linux 的 Jenkins 机器上我得到了以下错误:

testSimple(com.project.ClientImplTest): IOException parsing XML document from file [/data/continuous/workspace/sonar/main_proj/data/continuous/workspace/sonar/main_proj/target/main/WEB-INF/test-classes/applicationContext.xml]; nested exception is java.io.FileNotFoundException: data/continuous/workspace/sonar/main_proj/target/main/WEB-INF/test-classes/applicationContext.xml (No such file or directory)

我已经验证文件/data/continuous/workspace/sonar/main_proj/target/main/WEB-INF/test-classes/applicationContext.xml 确实存在。

为什么 getResource() 在 Linux 上找不到正确的路径。似乎出于某种原因它找到了 data/continous/... 而不是/data/continous/... ?因此 FileSystemXmlApplicationContext 可能会返回异常,因为它找不到文件。

谢谢

最佳答案

我在我的项目中遇到了同样的问题 - 它是由路径中的空格引起的 - 要处理这种情况,您需要使用 URL 的 toURI() 方法 - 执行以下操作:

ApplicationContext ctx;
URL urlApplicationContext = this.getClass().getClassLoader().getResource("applicationContext.xml");
if (urlApplicationContext != null) {
    File appCtxFile = new File(urlApplicationContext.toURI());
    ctx = new FileSystemXmlApplicationContext(new String[]{ appCtxFile.getAbsolutePath() });
} else {
    throw new RuntimeException("Cannot find XML file 'applicationContext.xml'");
}

关于java - 使用 getClassLoader().getResource 时 Linux 机器上的 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20123251/

相关文章:

Java split() 在索引 0 处有空间

java - 如何在Android键盘中设置关闭选项

java - GLSL 中没有出现纹理的可能原因有哪些?

linux - mmap/dev/mem时的缓存和 volatile 内存

linux - 无法从 Bash 关联数组中检索键/值对

java - 是否可以使用来自多个文本文件的数据在 java 中创建列表

java - 如何正确加密用 jackson 编写的 JSON 文件

Linux 应用程序在 pthread_create() 中崩溃

c - 如果缓冲区的大小小于 nbyte,为什么它可以工作?

python - 使用 os.system() 问题在 Ubuntu 上终止进程