Déterminer si un dossier est présent?
-
01-10-2019 - |
Question
Comment puis-je faire pour déterminer si un fichier ou le répertoire a été créé en Java?
Je veux essentiellement de créer un répertoire de données si l'on est pas déjà.
Merci.
La solution
Vous pouvez appeler File#exists()
pour déterminer si elle existe, mais vous pouvez aussi simplement appeler File#mkdirs()
pour créer automatiquement tout le chemin sinon exister.
Autres conseils
J'utilise généralement cette technique:
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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow