Search code examples
javafileutils

java.io.IOException: Failed to delete original file moveFileToDirectory


I'm trying to move the following files in the if statement by using FileUtils.moveFileToDirectory, after the files have been converted. JPG and gif files get moved to the new folder, but whenever the program finds an ICO file it won't move that file to the new folder and gives med the StackTrace: java.io.IOException: Failed to delete original file 'original path of the file' after copy to 'the new path for the file'. Here is the code for the method:

public void storeOriginalImages() {
    for(File file: model.getFileList()) {
        if(file.getName().endsWith(".GIF") || file.getName().endsWith(".gif") || file.getName().endsWith(".JPG") 
                || file.getName().endsWith(".jpg")  || file.getName().endsWith(".ico") || file.getName().endsWith(".ICO")
                || file.getName().endsWith(".BMP") || file.getName().endsWith(".bmp")) {
            System.out.println("in copy else");
            File illegalExtension = new File(file.getAbsolutePath());
            File illegalExtensionDest = new File(model.getTargetexcelFilepath() + "/" + model.getFolderName() + "_img_backup");
            System.out.println(illegalExtension + "/" + illegalExtensionDest);

            try {
                FileUtils.moveFileToDirectory(illegalExtension, illegalExtensionDest, true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

This is how the ICO file is converted to png:

else if(s.getName().endsWith(".ico") || s.getName().endsWith(".ICO")) {
            List<BufferedImage> bi = ICODecoder.read(new File(s.getAbsolutePath()));
            System.out.println("reading");
            ImageIO.write(bi.get(0), "png", new File(s.getParentFile().getAbsoluteFile(), fileNameWithOutExt + ".png"));
            System.out.println("Ico was converted.");
        }

Solution

  • I took your example and edited a bit. It seems when ICODecoder try to read from file using the stream it did not close it properly so you need to close it in your code. Here is the working example

    File oldFile = new File("a.ico");
    try (InputStream inputStream = new FileInputStream(oldFile)) {
         List<BufferedImage> bi = ICODecoder.read(inputStream);
         ImageIO.write(bi.get(0), "png", new File("a" + ".png"));
    
    } catch (IOException e) {
        LOG.error("Something happend", e);
    }
    FileUtils.moveFile(oldFile, new File("a.jpg"));
    

    You need to close the input stream before moving the file.