zoukankan      html  css  js  c++  java
  • 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 "";
        }
    
  • 相关阅读:
    poj 1113 wall(凸包裸题)(记住求线段距离的时候是点积,点积是cos)
    Atcoder(134)E
    poj 1696 极角排序(解题报告)
    poj 1410 (没做出来,记得闲着没事看看这道题)
    poj1066 线段相交简单应用(解题报告)
    poj 2653 线段相交裸题(解题报告)
    poj 1269
    要习惯用vector代替数组
    在 Angularjs 中$state.go 如何传递参数
    CSS实现内容超过长度后以省略号显示
  • 原文地址:https://www.cnblogs.com/no8g/p/13415588.html
Copyright © 2011-2022 走看看