Determinar si una carpeta está presente?
-
01-10-2019 - |
Pregunta
¿Cómo hago para determinar si un archivo o directorio ha sido creado en Java?
Básicamente quiero crear un directorio de datos si uno no está ya presente.
Gracias.
Solución
Puede llamar File#exists()
para determinar si existe, pero también se puede llamar simplemente File#mkdirs()
para crear automáticamente toda la ruta de acceso si no existe.
Otros consejos
Me suelen utilizar esta técnica:
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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow