相关疑难解决方法(0)

从jar中读取资源文件

我想从我的jar中读取资源,如下所示:

File file;
file = new File(getClass().getResource("/file.txt").toURI());
BufferredReader reader = new BufferedReader(new FileReader(file));

//Read the file
Run Code Online (Sandbox Code Playgroud)

并且它在Eclipse中运行时工作正常,但是如果我将它导出到jar中运行它就会出现IllegalArgumentException:

Exception in thread "Thread-2"
java.lang.IllegalArgumentException: URI is not hierarchical
Run Code Online (Sandbox Code Playgroud)

而且我真的不知道为什么,但经过一些测试我发现如果我改变了

file = new File(getClass().getResource("/file.txt").toURI());
Run Code Online (Sandbox Code Playgroud)

file = new File(getClass().getResource("/folder/file.txt").toURI());
Run Code Online (Sandbox Code Playgroud)

然后它的工作正好相反(它适用于jar而不是eclipse).

我正在使用Eclipse,我的文件夹在一个类文件夹中.

java resources jar file embedded-resource

207
推荐指数
5
解决办法
28万
查看次数

Java8中的"Autocloseable"数组或集合

Autocloseable应始终使用try-with-resources.至少Intellij检查表明了这一点.所以,如果我有一个生成Foo该实现的代码,Autocloseable我应该这样做:

try (final Foo foo = getFoo()) {
    foo.doSomething();
}
Run Code Online (Sandbox Code Playgroud)

但是如果我有功能返回Foo[]怎么办?或接受Foo[](或Collection<Foo>)作为其参数的函数?

我怎么用它try-with-resources?查看以下功能:

Foo[] getFoos();
doAll(Foo... foo);
Run Code Online (Sandbox Code Playgroud)

我想做点什么 doAll(getFoos())

我怎样才能做到这一点?

java java-8 try-with-resources autocloseable

7
推荐指数
2
解决办法
1322
查看次数