Java Files  «Prev  Next»


Lesson 14

Java Files Directories Conclusion

This module discussed
  1. how to work with files and directories using the java.io.File class
  2. how to find out what files already exist
  3. how to create new files
  4. how to determine information about a file, such as its size
  5. how to move around in directories, how to switch from one to another, and how to list their contents
  6. the difference between a random access file and a sequential access file
  7. about the methods useful for working with random access files
File Navigation and I/O: There are several other classes that we would be going through to get to know the basics of File Navigation and I/O.

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. For complete detail check a list of all the methods which you can call on File object and what are related to directories.

Creating Directories

There are two useful File utility methods, which can be used to create directories:
  1. The 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.
  2. The 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 m ain(String args[]) {
  String dirnam e = "/tm p/user/java/bin";
  File d = new File(dirnam e);
  // Create directory now.
  d.m kdirs();
 }
}

Compile and execute above code to create "/tmp/user/java/bin".
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.
In the next module, you will learn how to let the user select files with java.awt.FileDialog and java.awt.FilenameFilter.