1

我想删除日志目录中的旧日志文件。要删除超过 6 个月的日志文件,我编写了如下脚本

查找 /dnbusr1/ghmil/BDELogs/import -type f -mtime +120 -exec rm -f {} \;

通过使用此脚本,我可以删除旧文件,但是如何使用 java 调用此脚本?

4

5 回答 5

3

使用java.lang.Runtime.exec()

于 2009-01-23T04:21:20.870 回答
3

如果可移植性是一个问题,阻止您使用 Runtime.exec() 运行,那么使用 File 和 FilenameFilter 在 Java 中编写此代码非常简单。

编辑:这是删除目录树的静态方法...您可以很容易地添加过滤逻辑:

static public int deleteDirectory(File dir, boolean slf) {
    File[]                              dc;                                     // directory contents
    String                              dp;                                     // directory path
    int                                 oc=0;                                   // object count

    if(dir.exists()) {
        dir=dir.getAbsoluteFile();

        if(!dir.canWrite()) {
            throw new IoEscape(IoEscape.NOTAUT,"Not authorized to delete directory '"+dir+"'.");
            }

        dp=dir.getPath();
        if(dp.equals("/") || dp.equals("\\") || (dp.length()==3 && dp.charAt(1)==':' && (dp.charAt(2)=='/' || dp.charAt(2)=='\\'))) {
            // Prevent deletion of the root directory just as a basic restriction
            throw new IoEscape(IoEscape.GENERAL,"Cannot delete root directory '"+dp+"' using IoUtil.deleteDirectory().");
            }

        if((dc=dir.listFiles())!=null) {
            for(int xa=0; xa<dc.length; xa++) {
                if(dc[xa].isDirectory()) {
                    oc+=deleteDirectory(dc[xa]);
                    if(!dc[xa].delete()) { throw new IoEscape(IoEscape.GENERAL,"Unable to delete directory '"+dc[xa]+"' - it may not be empty, may be in use as a current directory, or may have restricted access."); }
                    }
                else {
                    if(!dc[xa].delete()) { throw new IoEscape(IoEscape.GENERAL,"Unable to delete file '"+dc[xa]+"' - it may be currently in use by a program, or have restricted access."); }
                    }
                oc++;
                }
            }

        if(slf) {
            if(!dir.delete()) { throw new IoEscape(IoEscape.GENERAL,"Unable to delete directory '"+dir+"' - it may not be empty, may be in use as a current directory, or may have restricted access."); }
            oc++;
            }
        }
    return oc;
    }
于 2009-01-23T06:41:12.070 回答
2

当您只想调用您描述的命令时:

Runtime r = Runtime.getRuntime();
Process process = r.exec("find /dnbusr1/ghmil/BDELogs/import -type f -mtime +120 -exec rm -f {} \\;"); //$NON-NLS-1$
process.waitFor();

如果您想调用多个命令,请使用 Chris Jester-Young 回答。exec 方法还可以定义您要使用的文件。其他答案链接方法描述。

于 2009-01-23T07:08:48.393 回答
1

在 Java 中使用系统调用是可能的,但通常不是一个好主意,因为您将失去代码的可移植性。您可以查看Ant并使用类似purge task的东西。

于 2009-01-23T04:23:28.960 回答
1

添加到 Crashworks 的答案中,您在以下参数中调用cmdarray

new String[] {"find", "/dnbusr1/ghmil/BDELogs/import", "-type", "f",
    "-mtime", "+120", "-exec", "rm", "-f", "{}", ";"}

如果您find支持该-exec ... {} +语法,";"请将末尾的 更改为"+". 它将使您的命令运行得更快(它将rm一次调用一批文件,而不是每个文件一次)。

于 2009-01-23T04:32:14.967 回答