我正在尝试读取资源文件夹中的文本文件进行测试。我已经尝试了至少 3 种在 Windows 上正常工作的不同实现,但它们在 Linux 上都失败了。
当前项目看起来像
/src/test/java
/com/my/app/util/Class_needs_text.java
/src/test/resources
/com/my/app/util/text_file.txt
Class_needs_text.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() 时,该类会将调用委托(delegate)给它的类加载器,我不确定 unix 和 windows JVM 之间是否有区别。不应该在操作系统上产生差异,因为正在加载类的类加载器应该对资源具有相同的可见性。
如果您尝试在静态方法中加载资源,您可以尝试获取类加载器。
Class_needs_text.class.getClassLoader().getResource(LOADTHIS);
如果你在非静态方法中
this.getClass().getResource(LOADTHIS);
关于java - 从 Linux 上的资源加载文本文件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21892746/