美文网首页
java代码清理磁盘空间(删除除了一些文件之外的文件)

java代码清理磁盘空间(删除除了一些文件之外的文件)

作者: 我还是老油条 | 来源:发表于2023-10-19 10:09 被阅读0次

1.项目中需要删除一些文件之外的文件,来清理磁盘空间

话不多说,直接上代码
需要执行的命令

find /test/server/test_case -type f -not -name 2134124B -not -name 6328572834759285B -delete

转换为java代码

   private void deleteFile(String audioPath,List<String> fileId) {
        Runtime run = Runtime.getRuntime();
        BufferedReader in = null;
        PrintWriter out = null;
        Process proc = null;
        try {
            log.info("删除{}文件开始", audioPath);
            //预存想要执行的命令
            List<String> commands = new ArrayList<>();
            //进入当前用户bin目录,也可替换成自己想要的目录
            commands.add("cd ~/bin");
            String findCmd = String.format("find %s -type f -not -name  ", audioPath);
            String join = StringUtils.join(fileId, " -not -name ");
            String deleteStr = " -delete";
            String cmd=findCmd+join+deleteStr;
            log.info("cmd:{}",cmd);
            commands.add(cmd);
            proc = run.exec("/bin/bash", null, null);//通用的,不用动。
            in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
            //开始执行命令
            for (String line : commands) {
                log.info("执行命令:" + line);
                out.println(line);
            }
            // 这个命令必须执行,否则in流不结束。
            out.println("exit");
            in.readLine();
            int waitFor = proc.waitFor();
            log.info("waitFor:{}",waitFor);
            log.info("删除{}文件结束", audioPath);
        } catch (IOException e1) {
            e1.printStackTrace();
            log.error("调用IO异常", e1);
        } catch (InterruptedException e2) {
            e2.printStackTrace();
            log.error("异常中断", e2);
        } catch (Exception e3) {
            e3.printStackTrace();
            log.error("请求失败", e3);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
                if (proc != null) {
                    proc.destroy();
                }
            } catch (Exception ex) {
                log.error("调用in.close Exception");
            }
        }

    }

替换掉其中的 path 和fileId 执行即可

相关文章

网友评论

      本文标题:java代码清理磁盘空间(删除除了一些文件之外的文件)

      本文链接:https://www.haomeiwen.com/subject/bykhidtx.html