我正试图读取我的资源文件夹中用于测试的文本文件。我已经尝试了至少3种在windows上正常工作的不同实现,但是在linux上都失败了。
当前项目看起来像

/src/test/java
  /com/my/app/util/Class_needs_text.java
/src/test/resources
  /com/my/app/util/text_file.txt

类需要文本.java
...
private static final String LOADTHIS = "/com/my/app/util/text_file.txt";
private static final String LOADTHAT = "text_file.txt";
// both of these work on windows, but not linux
java.net.URL url = Class_needs_text.class.getResource(LOADTHIS);
java.nio.file.Path resPath = java.nio.file.Paths.get(url.toURI());
fileContents = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8");

我已经检查了linux,并且文本文件在构建时被复制到两个类文件夹目录中。(/src/test/resources/com/my/app/util/text_file.txt到
./target/test classes/com/my/app/util/text_file.txt)
抱歉,如果这太冗长了。cliffs:我需要在windows和linux中读取位于文本文件中的资源文件夹的内容。

最佳答案

当对类调用getResource()时,该类会将该调用委托给其类加载器,我不确定Unix和Windows JVM之间是否存在差异。在操作系统上不应该有区别,因为加载类的类加载器应该对资源具有相同的可见性。
如果试图在静态方法中加载资源,可以尝试获取类加载器。

Class_needs_text.class.getClassLoader().getResource(LOADTHIS);

如果您使用的是非静态方法
this.getClass().getResource(LOADTHIS);

09-04 16:17
查看更多