Program to Create Directory - Single and multiple (i.e. parent and child directories) in java file IO

In this post we’ll write >
  • Program 1 to Create Directory - Single directory in java file IO >
  • Program 2  to Create Directory - multiple (i.e. parent and child directories) in java file IO >

Program 1 to Create Directory - Single directory in java file IO >
Create Single Directory
java.io.File's mkdir() method creates directory

Example - create C:\parentDirectory



when mkdir() method >
returns true  - if directory has been created successfully.
returns false - if directory creation failed


import java.io.File;
/** JavaMadeSoEasy.com */
public class CreateDirectory {
   public static void main(String... args) {
          String directory = "C:/superDirectory";
          File file = new File(directory);
          if (!file.exists()) { // create directory only if directory doesn't exists
                 if (file.mkdir()) {
                       System.out.println(directory + " created successfully");
                 } else {
                       System.out.println(directory + " creation failed");
                 }
          } else {
                 System.out.println(directory + " already exists");
          }
   }
}
/* OUTPUT
C:/superDirectory created successfully
*/


Must read Directory operations - identify, delete, copy, traverse.


Program 2  to Create Directory - multiple (i.e. parent and child directories) in java file IO >

Create multiple Directory (i.e. parent and child directories)
java.io.File's mkdirs() method creates directory, including parent directories that doesn't exists.

Example - create C:\parentDir\childDir, where even C:\parentDir doesn't exists
 First C:\parentDir will be created than C:\parentDir\childDir will be created


when mkdirs() method >
returns true  - if directory has been created successfully.
returns false - if directory creation failed (parent directory may have been created)


import java.io.File;
/** JavaMadeSoEasy.com */
public class CreateMultipleDirectory {
   public static void main(String... args) {
          String directory = "C:/superDir/childDir";
          File file = new File(directory);
          if (!file.exists()) { // create directory only if directory doesn't exists
                 if (file.mkdirs()) {
                    System.out.println(directory + " created successfully");
                 } else {
                       System.out.println(directory + " creation failed");
                 }
          } else {
                 System.out.println(directory + " already exists");
          }
   }
}
/* OUTPUT
C:/superDir/childDir created successfully
*/



RELATED LINKS>

Program to Identify File or Directory - in java file IO | And in java 7 using java.nio.file


2 Program to Delete a Directory


Copy a Directory


Traverse a Directory (all sub-directories and files) in 2 ways




No comments:

Post a Comment