2013-09-26 32 views
0

我的目標是刪除一個文件中存在的使用java程序linux的一些目錄。我有以下行:如何刪除當前文件中的某些目錄在linux編程

java.lang.Runtime.getRuntime().exec("/bin/rm -f " + fileToDelete.getAbsolutePath()); 

但我讀到,從Java程序使用Linux命令將是一個昂貴的操作。任何人都可以讓我知道如果有另一種方式做到這一點?

回答

4

如何File#delete()

boolean isFileDeleted = fileToDelete.delete(); 
+0

我從http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files看到。 html#delete(java.nio.file.Path)taht「在某些操作系統上,當它打開並被此Java虛擬機或其他程序使用時,可能無法刪除文件」,在這種情況下,我可能需要強制刪除此文件即使其打開。我認爲「rm -f」這樣做。如何實現這一目標? – user2349990

+0

我不建議刪除打開的文件。如果還有未記錄的數據呢?我建議確保所有打開的文件先關閉。請記住它在_this_ JVM中,所以你可以控制這個 – Reimeus

+0

從我記得Windows將阻止刪除打開的文件,但Linux不會。你有沒有嘗試刪除這樣的打開文件? – blalasaadri

2

你可以使用一個File對象,因爲這樣的:

// initializes your file with your full path (or use your "fileToDelete" variable) 
File file = new File("myFile"); 
// attempts to set the file writable and returns boolean result 
System.out.println("Could set file writable: " + file.setWritable(true)); 
// attempts to delete the file and returns boolean result 
System.out.println("Deleted succesfullly: " + file.delete()); 

許可/刪除操作可能會拋出一個未經檢查SecurityException

0
if(file.exists()) 
    boolean isSuccessful = file.delete(); 
0

試試這個,它工作在我的Linux

File f= new File("Path"); 
try { 
    java.lang.Runtime.getRuntime().exec("rm -f " + f.getAbsolutePath()); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
相關問題