zoukankan      html  css  js  c++  java
  • 解决File.delete()删除不掉文件

    首先注意两点:

    1. 此文件被使用的时候无法删除(比如网络输出没关闭流)

    2. 判断此文件是否存在再做删除(exists)

    3. 删除文件夹之前先删除文件夹下的所有文件(递归解决)

    4. 判断是否删除成功会有返回值,文件名错了的话,删除文件不会报错。(new File("x://123.txt"),但是123.txt不存在,不报错)

      // 输出文件流
                    ou = resp.getOutputStream();
                    in = report.getInputStream();
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        ou.write(bufferOut, 0, bytes);
                    }
                    in.close();
                    ou.flush();
                    ou.close();//关掉输出流,否则文件无法删除
     
    /**
         * 删除报表包含的临时文件
         */
        public void delete() {
            if (files != null) {
                Iterator<File> iter = files.iterator();
                while (iter.hasNext()) {
                    File temp = iter.next();
                    if(temp.exists()){
                        temp.delete();
                        logger.debug("文件:" + temp.getAbsolutePath() + " 删除成功!");
                    }else{
                        logger.debug("文件:" + temp.getAbsolutePath() + "不存在!");
                    }
                }
                files = null;
            }
            if (file != null) {
                if(file.exists()){
                    file.delete();
                    logger.debug("文件:" + file.getAbsolutePath() + " 删除成功!");
                    file = null;
                }else{
                    logger.debug("文件:" + file.getAbsolutePath() + " 不存在!");
                }
                file = null;
            }
        }
  • 相关阅读:
    【JAVA】java 堆溢出分析
    【数据结构】链表的基本学习 实现
    【其他】博客园自定义样式指南
    【JAVA】一些好用的开源java类库
    【Shell】Shell 常用命令
    【Spring】Spring Boot 要点整理
    【数据库】Mysql 连接相关
    【Linux】Shell 参数解析
    Erlang 中类型转换
    erlang 中 maps 练习
  • 原文地址:https://www.cnblogs.com/ae6623/p/4416449.html
Copyright © 2011-2022 走看看