2013-02-08 112 views
4

處理將在Linux Web服務器上運行以從特定目錄中刪除日誌的應用程序,但是我一直收到FileNotFound異常。當文件存在時,ProcessBuilder給出「文件未找到」異常

下面是代碼:

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 /家庭/根/ multicraft /服務器工作完全正常。

我也試着:

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

回答

12

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*"...); 
+0

感謝您的回答,沒有更多的錯誤,但它並沒有刪除任何文件。有關更多信息,該命令通常需要幾秒鐘才能完成,但在此行執行期間沒有暫停。這裏是更新後的代碼行 - 「find」,「/ home/root/multicraft/servers /」,「-name」,「'* CoreData *」,「-delete」 –

+0

您是否有名爲'CoreData 「那裏?我可以看到你從模式的開頭和結尾刪除了'*'。 – Isaac

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>應該理想地/箱或/ 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