gpt4 book ai didi

java - 关闭 BufferedImage 以便我可以删除它?

转载 作者:行者123 更新时间:2023-12-01 16:47:08 25 4
gpt4 key购买 nike

我使用ImageIO.read(File file)函数打开了一个图像,它返回了BufferedImage。我从该图像中读取了像素,现在我想将其从文件系统中删除。问题是 file.delete() 返回 false。调用 Files.delete(file.toPath()) 会引发异常:

java.nio.file.FileSystemException: C:\<file_location>\1517053169520.png: The process cannot access the file because it is being used by another process.

为了便于阅读,我缩短了路径。

这是代码片段:

public void test (File file) {
BufferedImage image = ImageIO.read(file);
byte[] pixels = ((DataBufferByte)image.getRaster().getDataBuffer()).getData();
// I do a bunch of things here, but I don't modify the pixels
image.flush();

/* I tried this too, but I know that GC doesn't have to be called immediately when I make a call to System.gc()

image = null;
System.gc();

*/

Files.delete(file.toPath());
}

所以,我的问题是:如何释放该文件,以便将其删除?

最佳答案

有一个issue reported some time ago with a similar scenario 。以下代码片段应该通过释放流来解决该问题:

BufferedImage image = null;
InputStream stream = null;
try {
stream = new FileInputStream(file);
image = ImageIO.read(stream);

} catch (Exception ex) {
log.error("Image could not be read: "+file);

} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException ex) {
log.error("ERROR closing image input stream: "+ex.getMessage(), ex);
}
}
}

关于java - 关闭 BufferedImage 以便我可以删除它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48475492/

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