gpt4 book ai didi

java - 当相应的 Stream 关​​闭时,Java FileChannel 锁是否关闭,或者我是否必须显式关闭它们?

转载 作者:搜寻专家 更新时间:2023-11-01 01:38:29 26 4
gpt4 key购买 nike

例如,我的代码目前看起来像下面这样。我需要显式调用 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
}

最佳答案

根据 FileLock 的 javadoc :

"A file-lock object is initially valid. It remains valid until the lock is released by invoking the release method, by closing the channel that was used to acquire it, or by the termination of the Java virtual machine, whichever comes first."

...我假设关闭流会关闭底层 channel 。

关于java - 当相应的 Stream 关​​闭时,Java FileChannel 锁是否关闭,或者我是否必须显式关闭它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4551759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com