1

根据AutoCloseable接口的定义,我
必须调用所有实例。 即我必须这样写。 close()

try(A a = new A()){
    //do something
}

java.sound.sampled.SourceDataLine接口中,
或更常见的是,在java.sound.sampled.Line接口中,
是否需要调用所有实例, 或者我必须仅在调用后close()调用?
close() 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
}  
4

2 回答 2

0

看来你是想多了。

只是图像 try-with-resources 将不存在并写下您的代码,就像您在 Java 1.7 之前所做的那样。

当然,你最终会得到类似的东西:

Whatever somethingThatNeedsClosing = null;
try {
  somethingThatNeedsClosing = ...
  somethingThatNeedsClosing.whatever();
} catch (NoIdeaException e) {
  error handling
} finally {
  if (somethingThatNeedsClosing != null) {
    somethingThatNeedsClosing.close()
  }
}

Try-with-resources 仅允许您相应地减少此示例。

换句话说:try-with-resources 允许您定义一个(或多个)将在 try 块中使用的资源;那最终将被关闭。如:为 try ... 声明的每个资源都将被关闭。

更具体地说:不要考虑资源的其他实例。专注于当前正在处理的问题。

于 2016-09-04T06:30:59.333 回答
0

您的实际问题应该是“close()数据线未打开时打电话有害吗?” 答案是“不”,所以你可以简单地使用

try(SourceDataLine sdl = AudioSystem.getSourceDataLine(audioFormat)) {
    sdl.open(audioFormat, bufferSize);
    // work with sdl
}
catch(LineUnavailableException ex) {
    throw new RuntimeException(ex);
}

请注意,javax.sound.sampled.Line在 Java 7 中已故意将其更改为 extend AutoCloseable,其唯一目的是允许在 try-with-resource 语句中使用资源。

于 2016-09-20T13:19:19.280 回答