根据AutoCloseable接口的定义,
我必须为close()调用ALL实例。
我必须这样写。
try(A a = new A()){
//do something
}在java.sound.sampled.SourceDataLine接口中,
或者更常见的是,在java.sound.sampled.Line接口中,
是否需要为所有实例调用,
还是我必须在close() 打电话给 open()之后才打电话给open()?
如果正式文档明确规定只有在close时我才必须使用isOpened,
我想写成这样。但我找不到人提。
//can I write like this ?
SourceDataLine sdl;
try{
sdl = AudioSystem.getSourceDataLine(audioFormat);
sdl.open(audioFormat,bufferSize);
}catch(LineUnavailableException ex){
throw new RuntimeException(null,ex);
}
try(SourceDataLine sdlInTryWithResources = sdl){
//do something
} 发布于 2016-09-20 13:19:19
您的实际问题应该是“当数据行尚未打开时调用close()是否有害?”答案是“不”,所以你可以简单地用
try(SourceDataLine sdl = AudioSystem.getSourceDataLine(audioFormat)) {
sdl.open(audioFormat, bufferSize);
// work with sdl
}
catch(LineUnavailableException ex) {
throw new RuntimeException(ex);
}请注意,在Java7中,javax.sound.sampled.Line被有意地更改为扩展AutoCloseable,其唯一目的是允许在带资源的try语句中使用资源。
发布于 2016-09-04 06:30:59
看来你想得太多了。
就像以前的Java1.7那样,只需映像一下试用资源就不存在并写下您的代码。
可以肯定的是,你最后的下场是:
Whatever somethingThatNeedsClosing = null;
try {
somethingThatNeedsClosing = ...
somethingThatNeedsClosing.whatever();
} catch (NoIdeaException e) {
error handling
} finally {
if (somethingThatNeedsClosing != null) {
somethingThatNeedsClosing.close()
}
}使用资源尝试只允许您相应地减少此示例。
换句话说:使用资源的尝试允许您定义一个(或多个)资源,这些资源将在try块中使用,并且最终将被关闭。如:为尝试而声明的每个资源.将被关闭。
更具体地说:不要考虑资源的其他实例。把注意力集中在你目前正在处理的问题上。
https://stackoverflow.com/questions/39314003
复制相似问题