Monday, June 1, 2015

Directory in Java


Directories in Java:

A directory is a File which can contains a list of other files and directories.
You use File object to create directories, to list down files available in a directory.

Creating Directories:

There are two useful File utility methods, which can be used to create directories:

  mkdir( ):
method creates a directory, returning true on success and false on failure.
Failure indicates that the path specified in the File object already exists, or that
the directory cannot be created because the entire path does not exist yet.

  mkdirs():
  method creates both a directory and all the parents of the directory.
 
Following example creates "/tmp/user/java/bin" directory:

import java.io.File;

public class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}

Compile and execute above code to create "/tmp/user/java/bin".

Note: Java automatically takes care of path separators on UNIX and Windows as per
conventions. If you use a forward slash (/) on a Windows version of Java,
the path will still resolve correctly.

No comments:

Post a Comment