我想从我的jar中读取资源,如下所示:
File file;
file = new File(getClass().getResource("/file.txt").toURI());
BufferedReader reader = new BufferedReader(new FileReader(file));
//Read the file
当在Eclipse中运行它时,它工作得很好,但是如果我将它导出到一个jar中,然后运行它,就会有一个IllegalArgumentException:
Exception in thread "Thread-2"
java.lang.IllegalArgumentException: URI is not hierarchical
我真的不知道为什么,但通过一些测试,我发现如果我改变
file = new File(getClass().getResource("/file.txt").toURI());
至
file = new File(getClass().getResource("/folder/file.txt").toURI());
然后它正好相反(它可以在jar中工作,但不能在eclipse中工作)。
我使用的是Eclipse,我的文件所在的文件夹是一个class文件夹。
发布于 2017-06-27 23:31:20
我以前遇到过这个问题,所以我采取了后备的加载方式。基本上,第一种方法是在.jar文件中工作,第二种方法是在eclipse或其他集成开发环境中工作。
public class MyClass {
public static InputStream accessFile() {
String resource = "my-file-located-in-resources.txt";
// this is the path within the jar file
InputStream input = MyClass.class.getResourceAsStream("/resources/" + resource);
if (input == null) {
// this is how we load file within editor (eg eclipse)
input = MyClass.class.getClassLoader().getResourceAsStream(resource);
}
return input;
}
}
发布于 2019-03-07 03:31:18
问题是某些第三方库需要文件路径名,而不是输入流。大多数答案都没有解决这个问题。
在这种情况下,一种解决方法是将资源内容复制到临时文件中。下面的示例使用jUnit的TemporaryFolder
。
private List<String> decomposePath(String path){
List<String> reversed = Lists.newArrayList();
File currFile = new File(path);
while(currFile != null){
reversed.add(currFile.getName());
currFile = currFile.getParentFile();
}
return Lists.reverse(reversed);
}
private String writeResourceToFile(String resourceName) throws IOException {
ClassLoader loader = getClass().getClassLoader();
InputStream configStream = loader.getResourceAsStream(resourceName);
List<String> pathComponents = decomposePath(resourceName);
folder.newFolder(pathComponents.subList(0, pathComponents.size() - 1).toArray(new String[0]));
File tmpFile = folder.newFile(resourceName);
Files.copy(configStream, tmpFile.toPath(), REPLACE_EXISTING);
return tmpFile.getAbsolutePath();
}
发布于 2020-09-10 09:04:36
在我的案例中,我最终做到了
import java.lang.Thread;
import java.io.BufferedReader;
import java.io.InputStreamReader;
final BufferedReader in = new BufferedReader(new InputStreamReader(
Thread.currentThread().getContextClassLoader().getResourceAsStream("file.txt"))
); // no initial slash in file.txt
https://stackoverflow.com/questions/20389255
复制相似问题