【发布时间】:2011-02-12 03:38:39
【问题描述】:
如何确定文件或目录是否已在 Java 中创建?
如果还没有数据目录,我基本上想创建一个数据目录。
谢谢。
【问题讨论】:
标签: java file filesystems io java-io
如何确定文件或目录是否已在 Java 中创建?
如果还没有数据目录,我基本上想创建一个数据目录。
谢谢。
【问题讨论】:
标签: java file filesystems io java-io
可以调用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
【讨论】: