1

我将如何确定是否已在 Java 中创建了文件或目录?

如果数据目录尚不存在,我基本上想创建一个数据目录。

谢谢。

4

2 回答 2

4

您可以调用File#exists()以确定它是否存在,但如果不存在,您也可以调用File#mkdirs()自动创建整个路径。

于 2010-04-25T18:14:48.437 回答
1

我通常使用这种技术:

    File folderLocation = new File("/blah/blah/mysystem/myfolder");

    if (folderLocation.exists()) {
        if (!folderLocation .isDirectory()) {
            throw new IOException("File-system item with path [" + folderLocation.getAbsolutePath() + "] exists but is not a folder.");
        }                
    } else {
        if (!folderLocation.mkdirs()) {
            throw new IOException("Could not create folder with path : " + folderLocation.getAbsolutePath());
        }
    }

    // we are guaranteed that the folder exists here
于 2010-04-25T19:27:49.687 回答