我开始使用thumbnailator库在Spring Boot项目中制作缩略图 但是,当我尝试删除文件时遇到了一个问题,我遇到一个异常,告诉我该文件正在被另一个进程使用。我对Java相当陌生,我不知道问题可能出在哪里以及应该停止/关闭哪个进程:
File originalFile = mediaUtils.saveFile(pathOriginal, file);
String path = mediaUtils.resolvePath(imageDir, name, false, image.getCreation());
mediaUtils.saveJPG(originalFile, file.getContentType(), WIDTH_IMAGE_SIZE, path);
String pathThumb = mediaUtils.resolvePath(imageDir, name, true, image.getCreation());
mediaUtils.saveJPG(originalFile, file.getContentType(), WIDTH_IMAGE_SIZE_THUMB, pathThumb);
public File saveFile(String filePath, MultipartFile file) {
try {
Path path = Paths.get(getPath(filePath));
Files.createDirectories(path.getParent());
Files.copy(file.getInputStream(), path);
return new File(path.toString());
} catch (IOException e) {
LOG.error("could not save file", e);
throw new FileException("could not create file: " + getPath(filePath), e);
}
}
private void saveJPG(InputStream imageInputStream, File file, String contentType, int newWidth, String outputPath) {
try {
// verify it is an image
if (!Arrays.asList("image/png", "image/jpeg").contains(contentType)) {
throw new IllegalArgumentException("The file provided is not a valid image or is not supported (should be png or jpeg): " + contentType);
}
// Create input image
BufferedImage inputImage = ImageIO.read(imageInputStream);
newWidth = newWidth > inputImage.getWidth() ? inputImage.getWidth() : newWidth;
double ratio = (double) inputImage.getWidth() / (double) inputImage.getHeight();
int scaledHeight = (int) (newWidth / ratio);
Path path = Paths.get(baseUrl + outputPath + ".jpg");
Thumbnails.of(file)
.size(newWidth, scaledHeight)
.toFile(path.toFile());
LOG.info("writing image to {}", path);
} catch (IOException e) {
LOG.error("could not write image", e);
}
}
感谢您的任何建议或帮助:)
答案 0 :(得分:0)
使用完输入流和文件后,应确保关闭它们。 否则,您提到的事情就会发生。一个进程确实阻止了您的文件。
因此,我建议不要使用简单的try-catch-blocks,而是使用try-with-resources,它将关闭基础流和文件。例如:
try(InputStream imageInputStream = new FileInputStream(...)) {
// do your stuff
}
括号中的代码完成或发生异常后,输入流将关闭。