FileOutputStream fos = new FileOutputStream(f, true);
FileChannel fileChannel = fos.getChannel();
FileWriter fileWriter = Channels.newWriter( fileChannel, Charset.forName("UTF-8").newEncoder(), -1 );
....
fileWriter.close()我收到了一个编译器警告,因为'fos‘没有关闭,我有一个资源泄漏。我假设,但到目前为止还未能证明,当我调用'fileWriter.close()‘时,资源就会被清理干净。
发布于 2016-08-11 01:04:19
不,这不是资源泄漏,但编译器不够聪明,无法解决这个问题。
当您关闭FileWriter时,它会关闭FileChannel,而这反过来又会关闭FileOutputStream。
当然,对于不同的JVM,情况可能不是这样,我只看过甲骨文的Java8 rt.jar中的代码。
由于它没有作为FileWriter的公共契约的一部分声明,所以显式关闭您创建的所有流是个好主意。
https://stackoverflow.com/questions/38885542
复制相似问题