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

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

谢谢。

有帮助吗?

解决方案

你可以打电话 File#exists() 确定是否存在,但您也可以致电 File#mkdirs() 如果不存在,则自动创建整个路径。

其他提示

我通常使用这种技术:

    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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top