使用将在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();
答案 0 :(得分:14)
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查找名为&#34; find /home/root/multicraft/servers/ -name '*.log' -delete
&#34;而不是find
的程序。
您必须将长命令分成几部分。如:
ProcessBuilder pb = new ProcessBuilder("find", ".", "-name", "'*CoreData*"...);
答案 1 :(得分: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
。