1

私のjUnit中には、次のスニペットがあります。

private String  session = "/tmp/session/";
private File    f;

@Before
public void setUp() {
    f = new File(session);
    f.mkdir();
}

@After
public void tearDown() {
    System.out.println("Directory deleted:   " + f.delete()); // always false
}

その間:

  • ディレクトリのアクセス許可は大丈夫です(drwxr-xr-x
  • ディレクトリにはいくつかのファイルが含まれています(-rw-r--r--
  • 所有権の問題なし(作成者ユーザーが削除)

何がf.delete()失敗するのでしょうか?f.delete()と同等ですrm -rfか?

4

3 に答える 3

6

空でないディレクトリを再帰的に削除する(そしてプロセスで車輪の再発明を行わない)最も簡単な方法は、既存のライブラリの機能を使用することです。たとえば、Apache CommonsのファイルutilsのFileUtils.deleteQuietly()メソッドは、次のことを指定します。

ファイルがディレクトリの場合は、それとすべてのサブディレクトリを削除します(...)削除するディレクトリは空である必要はありません

于 2012-07-24T17:01:57.730 に答える
3

File.deleteのAPIドキュメントから:

delete

public boolean delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname
denotes a directory, then the directory must be empty in order to be deleted.
Returns:
true if and only if the file or directory is successfully deleted; false otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete

ファイルへのアクセス

空である必要があるディレクトリについてのビットに注意してください。

于 2012-07-24T16:56:15.470 に答える
3

前に述べたように、ディレクトリを削除する前に、ディレクトリを空にする必要があります。ここにあなたが見るべき素晴らしいチュートリアルがあります。ディレクトリを削除する前にディレクトリを空にする必要recursive deleteがあるため、ディレクトリとそのすべてのファイルを削除する必要があります。

于 2012-07-24T16:59:54.703 に答える