0

私の目的は、Java プログラムを使用して、Linux に存在するディレクトリ内のファイルを削除することです。私はそれを行う次の行を持っています:

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

しかし、Java プログラムから Linux コマンドを使用すると、コストがかかる操作になると読みました。これを行う別の方法があるかどうか、誰かに教えてもらえますか?

4

4 に答える 4

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());

アクセス許可/削除操作は unchecked をスローする場合がありSecurityExceptionます。

于 2013-09-26T10:45:51.343 に答える
0
if(file.exists())
    boolean isSuccessful = file.delete();
于 2013-09-26T10:48:26.940 に答える
0

これを試してみてください、それは私のLinuxで動作します

File f= new File("Path");
try {
    java.lang.Runtime.getRuntime().exec("rm -f " + f.getAbsolutePath());
} catch (IOException e) {
    e.printStackTrace();
}  
于 2013-09-26T10:57:17.567 に答える