jdk1.8 AudioSystem 无法关闭流的问题

发布时间 2023-08-26 21:21:59作者: hligy

问题

首先说明 JDK 版本,Eclipse Temurin 1.8.0_382,写音频处理时遇到一个文件流无法关闭的问题。具体是javax.sound.sampled.AudioSystem#getAudioInputStream(java.io.File) 写在 try-with-resources 里,在 try-with-resources 结束的代码块外删除文件显示文件被占用,最后在 stackoverflow 找到了答案:audioinputstream close not releasing resources properly is there a workaround

其他

去稍微新一点的 jdk17 看了下这个方法的实现,发现方法变成 stackoverflow 的样子了:

final InputStream fileStream = new FileInputStream(file);
try {
    return getAudioInputStream(new BufferedInputStream(fileStream));
} catch (final Throwable e) {
    closeSilently(fileStream);
    throw e;
}

JDK8 不修复这个问题是有什么原因吗?有点好奇,再贴上 jdk bugs audioInputStream.close() does not release the resource,以后有时间再研究研究为什么 jdk8 无法释放资源

最后

尽早升级 jdk 吧