Friday, May 13, 2011

Create Sub-Directory From File Name in Java

Description:
You have a file name and you need to create a new directory in the folder where the file resides.

Solution:
The following method creates a new directory in the same directory as the file. If the directory exists already, it does nothing.
In other words, it makes sure the directory is there.
It accepts two strings as arguments, file name and sub-directory name.
boolean  createDirectory (String fname, String dirName) {
 //get the path to the parent directory
 String parent =  (new File(fname).getParent());
 //construct a new directory path
 String dirPath = parent+"\\" + dirName;

 File dir = new File(dirPath);

 if(!dir.exists()){
  boolean success = dir.mkdir();
  if (!success) {
   System.out.println("Directory creation failed");
   return false;
  }
 }
 return true;
}

A variation of the above method is the one that returns the path to the sub-directory:
public static String getDirectory(String fname, String dirName) {

  String parent =  (new File(fname).getParent());
  String dirPath = parent+"\\" + dirName;
  File dir = new File(dirPath);

  if(!dir.exists()){
   boolean success = dir.mkdir();
   if (!success) {
    System.out.println("Directory creation failed");
    return null;
   }
  }
  return dirPath;
 }



Another thing we could do is have the method create a sub-directory based on the file name without extension.
public static String getDirectoryFromFileName(String fname) {

  String parent =  (new File(fname).getParent());
  //extract a file name without extension from the path
  String name = getFileName(fname);
  String dirPath = parent+"\\" + name;

  File dir = new File(dirPath);

  if(!dir.exists()){
   boolean success = dir.mkdir();
   if (!success) {
    System.out.println("Directory creation failed");
    return null;
   }
  }
  return dirPath;
 }

No comments:

Post a Comment