Site icon Bytefreaks.net

Java: Given a path to a file, create the folders to it

Advertisements

Assuming you have a full path to a file you want to create but the folder to it might exist or not, you can use the following code in your program to check if the folder exists and if it doesn’t, create it.

//The file we want to create;
final String logFileName = "./someFolder/anotherFolder/etc/myFile.txt";
//We find the last occurrence of the File.separator value, which will allow us to separate the path from the filename
final int lastIndex = logFileName.lastIndexOf(File.separator);
//The actual path we want to make sure it exists
final String dirPath = logFileName.substring(0, lastIndex > 0 ? lastIndex : logFileName.length());
//We try to use the folder by assigning it to a File object
final File theDir = new File(dirPath);
//Make the check that the folder exists
if (!theDir.exists()) {
    //If the folder does not exist, create it
    theDir.mkdirs();
}
//Continue with execution

This post is also available in: Greek

Exit mobile version