2013-06-29 84 views
0

我有一個ProcessBuilder應刪除File.txt,然後重命名NewFile.txt。 問題是兩個文件都被刪除。任何想法爲什麼以及如何解決?ProcessBuilder刪除和重命名

public class MyProcessBuilder { 

    public static void main(String[] args){ 
     final ArrayList<String> command = new ArrayList<String>(); 

     // CREATE FILES 
     File file = new File("File.txt"); 
     File newFile = new File("NewFile.txt");  
     try{ 
      if(!file.exists()) 
       file.createNewFile(); 
      if(!newFile.exists()) 
       newFile.createNewFile(); 
     } catch(Exception e){} 

     // force remove File.txt 
     command.add("rm"); 
     command.add("-f"); 
     command.add("File.txt"); 

     // rename NewFile.txt to File.txt 
     command.add("mv"); 
     command.add("NewFile.txt"); 
     command.add("File.txt"); 

     final ProcessBuilder builder = new ProcessBuilder(command); 
     try { 
      builder.start(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

回答

3

的問題是,你正在運行一個命令,即

rm -f File.txt mv NewFile.txt File.txt 

這種無條件刪除名爲File.txtmvNewFile.txt文件。

你想把它分成兩個單獨的命令。

更好的是,使用File.delete()File.renameTo()。這不僅會給你更多的控制權,還會讓你的代碼更加便攜。

+0

謝謝。不幸的是,這回答了我的問題。我真正想要做的是:運行Program.jar,刪除Program.jar,將NewProgram.jar重命名爲Program.jar,運行Program.jar。因爲我正在運行Program.jar(File.txt),所以它不能被刪除。每個命令可以用一個ProcessBuilder解決嗎? – Grains

0

ProcessBuilder.start創建一個進程。你需要調用它兩次,因爲你有兩個命令:第一個是第一個命令,然後是第二個命令。

順便說一下,爲什麼你不使用Java的文件API呢?從Java執行此操作比處理啓動單獨流程的複雜性要容易得多,更不用說效率更高了。