Home Java Example Java Io Java Create Directory - Java Tutorial
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Java Create Directory - Java Tutorial

Advertisement
In the section of Java Tutorial you will learn how to create directory using java program.

Java Create Directory - Java Tutorial

     

Introduction

In the section, you will learn how a directory or subdirectories are created. This program also explains the process of creating all non-existent ancestor directories automatically. We will use the File class to crate the directory.

 File
The File class an abstract representation of file and directory pathnames. File class is used to interact with the files system.


Here is the code for creating directory and all non-existing ancestor directories:

import java.io.*;
class CreateDirectory 
{
 public static void main(String args[])
  {
  try{
  String strDirectoy ="test";
  String strManyDirectories="dir1/dir2/dir3";

  // Create one directory
  boolean success = (new File(strDirectoy)).mkdir();
  if (success) {
  System.out.println("Directory: " + strDirectoy + " created");
  }  
  
  // Create multiple directories
  success = (new File(strManyDirectories)).mkdirs();
  if (success) {
  System.out.println("Directories: " + strManyDirectories + " created");
  }

  }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}

Output of the program: 

C:\nisha>javac CreateDirectory.java

C:\nisha>java CreateDirectory
Directory: test created
Directories: dir1/dir2/dir3 created

C:\nisha>

This program takes inputs to create a directory "test" and subdirectories "dir1\dir2\dir3". the mkdir( ) method is used to create a single directory while the mkdirs( ) method is used to create multiple subdirectories.

Download the code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 17, 2007

Related Tutorials

Ask Questions?    Discuss: Java Create Directory - Java Tutorial   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com