java中File的delete()方法删除文件失败的原因和解决方案

通常来说:java file.delete()方法删除文件失败的原因有以下几个:

1、极有可能是文件的流没有关闭(我遇到的就是没有关闭文件的输入流);

2、被别的进程引用,可以手工删除试试(如果删除不了就证明被别的进程正在引用);

3、file是文件夹,而且不为空,file文件夹里还有别的文件夹或者是文件。

我的代码如下:

readTemplateFileContent()这个方法用来读取模板文件的内容,用到了流资源,但是用完之后没有关闭,导致删除文件失败;

    @Override
    public TemplateFile findByPath(String path) {
        File file = new File(path);
        if (!file.exists()) {
            throw new SystemException("模板不存在请检查!");
        }
        String parentPath = null;
        String[] fileParent = file.getParent().split("templates");
        if (fileParent.length == 1){
            parentPath = File.separator;
        }else {
            parentPath = fileParent[1];
        }
        TemplateFile templateFile = new TemplateFile();
        templateFile.setFileName(file.getName());
        templateFile.setFilePath(file.getAbsolutePath());
        templateFile.setParentPath(parentPath);
        
        // 这里是读取文件的内容,用到了下面写的方法,方法内有读写的文件流
        templateFile.setContent(this.readTemplateFileContent(file));
        return templateFile;
    }


    @Override
    public String readTemplateFileContent(File file) {
        ByteArrayOutputStream bos = null;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }

        } catch (Exception e) {
            throw new SystemException(e.getMessage());
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                log.error("读取模板失败");
            }

            // 当时删除不成功的原因就是没有下面的try...catch代码块,inputStream没有关闭
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error("读取模板失败, {}", e);
            }
        }
        try {
            return new String(bos.toByteArray(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error("读取模板失败");
        }

        return "";
    }
原文地址:https://www.cnblogs.com/no8g/p/13415588.html