我看到了这个例子,并没有看到close()
方法被调用于InputStream
上,那么prop.load()
会自动关闭流吗?还是例子中有错误?
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream(new File("abc.properties"));
new Properties().load(in);
System.out.println(in.read());
}
java.io.IOException:Stream Closed
。Properties.load(InputStream inStream)
的javadoc说:这个已经自Java 6开始就一直如此了。该方法返回后,指定的流保持打开状态。
InputStream
(如果需要,您可以添加 catch
和 finally
):try (InputStream is = new FileInputStream("properties.txt")) {
// is will be closed automatically
}
Properties.load()
没有关闭流,你需要手动关闭。整个示例的质量非常差,甚至在某些操作系统上都无法正常工作。不要依赖任意的互联网垃圾,请使用Oracle Java教程。 - user207421