5

处理将在 Linux Web 服务器上运行的应用程序以从某个目录中删除日志,但是我不断收到 FileNotFound 异常。

这是代码:

public static void deleteLOG() {
    try {
        ProcessBuilder probuilder = new ProcessBuilder("find /home/root/multicraft/servers/ -name '*.log' -delete");
        probuilder.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

和例外

java.io.IOException: Cannot run program "find . -name '*CoreData*' -delete" (in directory "/home/root/multicraft/servers"): error=2, No such file or directory
        at java.lang.ProcessBuilder.start(Unknown Source)
        at com.mcprohosting.com.nodecleanup.Preprocess.deleteCoreData(Preprocess.java:23)
        at com.mcprohosting.com.nodecleanup.handlers.CleanupHandler.executeCleanup(CleanupHandler.java:36)
        at com.mcprohosting.com.main.NodeCleaner.init(NodeCleaner.java:29)
        at com.mcprohosting.com.main.NodeCleaner.main(NodeCleaner.java:25)
Caused by: java.io.IOException: error=2, No such file or directory
        at java.lang.UNIXProcess.forkAndExec(Native Method)
        at java.lang.UNIXProcess.<init>(Unknown Source)
        at java.lang.ProcessImpl.start(Unknown Source)
        ... 5 more

但是命令 cd /home/root/multicraft/servers 工作得很好。

我也试过:

    ProcessBuilder probuilder = new ProcessBuilder("find . -name '*Backup*' -delete");
    probuilder.directory(new File("/home/root/multicraft/servers/"));
    probuilder.start();
4

2 回答 2

18

构造ProcessBuilder函数接收多个字符串 - 作为一个List<String>或可变数量的参数,每个类型String

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html#ProcessBuilder(java.util.List) http://docs.oracle.com/javase/1.5。 0/docs/api/java/lang/ProcessBuilder.html#ProcessBuilder(java.lang.String...)

您遇到了困难,因为您将整个命令作为一个字符串传递,导致 JVM 寻找一个名为“ find /home/root/multicraft/servers/ -name '*.log' -delete”的程序,而不是find.

您必须将长命令分成几部分。如:

ProcessBuilder pb = new ProcessBuilder("find", ".", "-name", "'*CoreData*"...);
于 2013-02-08T04:46:54.590 回答
1
    try {
        ProcessBuilder probuilder = new ProcessBuilder("<Absolute Path To>/find /home/root/multicraft/servers/ -name '*.log' -delete");
        probuilder.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

<Absolute Path To>理想情况下应该是 /bin 或 /usr/bin

ProcessBuilder probuilder = new ProcessBuilder("find /home/root/multicraft/servers/ -name '*Backup*' -delete");
probuilder.directory(new File("<Absolute Path To>"));
probuilder.start();

probuilder.directory期望工作目录在哪里find

于 2013-02-08T04:51:25.440 回答