当相应的 Stream 关闭时,Java FileChannel 锁是否也会关闭,或者我是否必须显式关闭它们?
例如,我的代码目前看起来如下所示。我是否需要显式调用lock.release
,还是在FileOutputStream
关闭时自动释放?
var os:FileOutputStream = null
var writer:PrintWriter = null
try {
os = new FileOutputStream(name, false)
val lock = os.getChannel().tryLock
if(lock != null) {
writer = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(os)))
(write stuff to file)
} else {
(error stuff)
}
} finally {
if(writer != null) writer.close
os.close
}
Eg, my code looks currently something like the following. Do I need to explicitly call lock.release
or is it automatically released when the FileOutputStream
is closed?
var os:FileOutputStream = null
var writer:PrintWriter = null
try {
os = new FileOutputStream(name, false)
val lock = os.getChannel().tryLock
if(lock != null) {
writer = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(os)))
(write stuff to file)
} else {
(error stuff)
}
} finally {
if(writer != null) writer.close
os.close
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据 FileLock 的 javadoc:
...我假设关闭流会关闭底层通道。
According to the javadoc for FileLock:
... and I assume that closing the stream closes the underlying channel.
想象它会被发布,但我很好奇,我在finally块中用这个检查了它:
这就是结果:
当你关闭编写器时,它似乎被清理了。
Imagined it would be released, but curious as I was I checked it with this in the finally block:
And this was the result:
Seems it get cleaned when you close the writer.
当我带着同样的疑问用谷歌搜索时,出现了这个问题。
没有找到绝对答案,我做了一些测试。
我可以确认,是的,只需关闭编写器即可释放锁。您甚至不需要手动关闭编写器下的流。
我的测试方式:
1) 我在 Eclipse 中以调试模式运行代码。
2) 写入并刷新文件后(关闭之前),我尝试使用 Windows 资源管理器删除该文件。正如预期的那样,由于锁定而失败。
3)一旦我单步执行 writer.close() 方法,但在完成运行之前,我再次尝试删除该文件。它毫无问题地删除了它。
这清楚地告诉我 close() 方法将导致锁被释放。
注意:以上仅适用于JDK的File类。扩展 java.io.File 的库的行为可能有所不同。例如,如果您使用 iSeries IfsJavaFile,则会出现连接内存泄漏,除非您还释放 iSeries 特定的服务器连接对象。
This question came up when I googled with the same doubt.
Not finding an absolute answer, I did some testing testing.
I can confirm that yes, simply closing the writer will release the locks. You do not even need to manually close the stream that is under the writer.
How I tested:
1) I run the code in Eclipse in debug mode.
2) After writing and flushing to the file (before closing) I attempted to delete the file using Windows Explorer. As expected it failed due to the lock.
3) Once I stepped through the writer.close() method, but before completing the run I attempted again to delete the file. It deleted it without a problem.
This clearly tells me that the close() method will cause the locks to be released.
NOTE: The above is only for the JDK's File class. Libraries that extend java.io.File might behave differently. For example if you use an iSeries IfsJavaFile you will have a connection memory leak unless you also release an iSeries-specific server connection object.