Warning: INSERT command denied to user 'dbo292345962'@'74.208.16.27' for table 'watchdog' query: INSERT INTO watchdog (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (0, 'php', '%message in %file on line %line.', 'a:4:{s:6:\"%error\";s:12:\"user warning\";s:8:\"%message\";s:398:\"INSERT command denied to user 'dbo292345962'@'74.208.16.27' for table 'captcha_sessions'\nquery: INSERT into captcha_sessions (uid, sid, ip_address, timestamp, form_id, solution, status, attempts) VALUES (0, 'd8a8d9a704f281db2bc07297cd95bd30', '54.81.76.147', 1414291943, 'comment_form', 'cb183167c8a9fe1a47efb934db7908ab', 0, 0)\";s:5:\"%file\";s:62:\"/homepages/25/d199835659/htdocs/ID/modules/captcha/captcha.inc\";s:5:\"%line\";i:99;} in /homepages/25/d199835659/htdocs/ID/includes/database.mysql.inc on line 135
Java: Create Directories Automatically | Inferno Development

Java: Create Directories Automatically

Have you ever had to categorize data on your hard drive, or prepare folders to put different images in? It takes a lot of time to manually create folders and sub-folders on your computer. However, Java has built-in methods to create directories for you. In this tutorial, I will show you how to take advantage of Java's built-in file methods.

Java has the methods called mkdir and mkdirs. These method are a part of java.io.File. Basically, mkdir will create create the directory for a given abstract pathname. On the other hand, mkdirs will do the same, but it will also create parent directories that do not exist. So basically, mkdirs will automatically handle potential errors, so we will use this for our code. They both return a boolean value of true or false, based up the success or failure of the directory creation.

So let us say we want a master directory, with multiple sub-level directories inside the master. Well, you could manually create these if you only needed thirty or so. But this would be easily solved with a Java program that implements a single for-loop to make each sub-level directory.

However, what if we needed multiple third-level directories inside of the sub-level directories? Well, manually making these directories is out of the question... so let's use a nested for-loop instead.

NOTE: Think about the time we would save to write a program for this. If we needed 90 sub-level directories and 90 third-level directories, that would be 8100 folders we would have to manually create.

So we need to ask the user for the name of the master, the prefix name of the sub-level directories, and the prefix name of each third-level directory. We will also need to find out how many sub-level and third-level directories are needed.

These requests can be easily solved using the Scanner method taught in my "Java Input and Output for Beginners" tutorial, with a little bit of code change:

// for Strings, use 'next()'
String name = s.next();

// for Integers, use 'nextInt()'
int number = s.nextInt();

In the same tutorial, I teach you how to concatenate a name. We will use this technique to concatenate the directories' prefixes and suffixes togethor. This example will show us how to concatanate a simple abstract pathnames:

String pathname = "C:/" + "test" + "/" + "sub";
String directory = pathname + "/thirdlevel";

So if we use this newly created directory, let's see an example of mkdirs() with it:

// Uses the directory variable from the last code example
new File(directory).mkdirs();

So now that we understand the basics, how about I show you some working code:

Working Code

// Joshua Du Lac
// Inferno Development

import java.io.File;
import java.util.Scanner;


public class CreateDirectories {
  public static void main(String[] args) {
         
                // Integer variables
                int numberSubLevel, numberThirdLevel;
                int i, j; // Indices
               
                // String variables
                String drive, topLevelTitle, subLevelTitle, thirdLevelTitle;
                String topLevelDirectory, subLevelDirectory, thirdLevelDirectory;

                // Scanner
                Scanner s = new Scanner(System.in);
               
                // Request input from user
                System.out.println("What is relative location (ex: C:/ or C:/test/one) ?");
                drive = s.next();

                System.out.println("Give a title to the top-level directory:");
                topLevelTitle  = s.next();
               
                System.out.println("How many sub-level directories do you want in " + topLevelTitle + "?");
                numberSubLevel = s.nextInt();
               
                System.out.println("Give a title to these sub-level directories:");
                subLevelTitle  = s.next();
               
                System.out.println("How many third-level directories in each sub-level directory?");
                numberThirdLevel = s.nextInt();

                System.out.println("Give a title to these third-level directories?");
                thirdLevelTitle  = s.next();
               
                // Directory Prefix Concatenation
                topLevelDirectory = drive + "/" + topLevelTitle;
                new File(topLevelDirectory).mkdirs();

                for(i = 1; i <= numberSubLevel; i++)
                {
                        // Directory Prefix Concatenation
                        subLevelDirectory = topLevelDirectory + "/" + subLevelTitle + i;
                        new File(subLevelDirectory).mkdirs();
                               
                        for(j = 1; j <= numberThirdLevel; j++)
                        {
                                // Directory Prefix Concatenation
                                thirdLevelDirectory = subLevelDirectory + "/" + thirdLevelTitle + j;
                                new File(thirdLevelDirectory).mkdirs();
                                       
                        }//for
                }//for
               
                System.out.println("Message: Finished");
  }
}

If you look closely, I use the concatenation technique a lot. This allows the code to play off of the last created directory. On top of that, we concatenate the new directory name, and use this pathname to create our directory.

Is there anything we can do to improve our code? Well, if you noticed, there is no response until the end. So what if you have an input size of 100 x 100. The program will run for a while with no response. So how about we take advantage of the fact that mkdirs() returns a boolean value?

We can create a method to print a message based upon the boolean value. We want to know whether or not the directory was created:

  static void checkDir(boolean event) {
          if(event == true)
                  System.out.println("Message: Created directory");
          if(event == false)
                  System.out.println("Error: mkdirs failed to create a directory");
  }

However, to use this new method, we need to call it from within our main code. Knowing that the boolean is returned from mkdirs(), let us pass it as a parameter to our checkDir method. When mkdirs() runs, it will return the boolean to checkDir(). Here is an example:

checkDir(new File(directory).mkdirs());

Final Code

// Joshua Du Lac
// Inferno Development

import java.io.File;
import java.util.Scanner;


public class CreateDirectories {
  public static void main(String[] args) {
         
                // Integer variables
                int numberSubLevel, numberThirdLevel;
                int i, j; // Indices
               
                // String variables
                String drive, topLevelTitle, subLevelTitle, thirdLevelTitle;
                String topLevelDirectory, subLevelDirectory, thirdLevelDirectory;
               
                // Scanner
                Scanner s = new Scanner(System.in);
               
                // Request input from user
                System.out.println("What is relative location (ex: C:/ or C:/test/one) ?");
                drive = s.next();

                System.out.println("Give a title to the top-level directory:");
                topLevelTitle  = s.next();
               
                System.out.println("How many sub-level directories do you want in " + topLevelTitle + "?");
                numberSubLevel = s.nextInt();
               
                System.out.println("Give a title to these sub-level directories:");
                subLevelTitle  = s.next();
               
                System.out.println("How many third-level directories in each sub-level directory?");
                numberThirdLevel = s.nextInt();

                System.out.println("Give a title to these third-level directories?");
                thirdLevelTitle  = s.next();
               

                // Directory Prefix Concatenation
                topLevelDirectory = drive + "/" + topLevelTitle;
                checkDir(new File(topLevelDirectory).mkdirs());

                for(i = 1; i <= numberSubLevel; i++)
                {
                        // Directory Prefix Concatenation
                        subLevelDirectory = topLevelDirectory + "/" + subLevelTitle + i;
                        checkDir(new File(subLevelDirectory).mkdirs());
                               
                        for(j = 1; j <= numberThirdLevel; j++)
                        {
                                // Directory Prefix Concatenation
                                thirdLevelDirectory = subLevelDirectory + "/" + thirdLevelTitle + j;
                                checkDir(new File(thirdLevelDirectory).mkdirs());
                                       
                        }//for
                }//for
               
                System.out.println("Message: Finished");
}

  static void checkDir(boolean event) {
          if(event == true)
                  System.out.println("Message: Created directory");
          if(event == false)
                  System.out.println("Error: mkdirs failed to create a directory");
  }
}

Now compile it, and try it out for yourself. See if you can switch it up to your liking or add another nested for-loop to add another teir of directories.

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.