JMU
Files and File Systems in Java
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


File Systems
Files and Directories in Java
Operating on File Objects
Operating on File Objects (cont.)
Operating on File Objects (cont.)

An Example

javaexamples/iobasics/Dir.java
import java.io.*;


/**
 * An implementation of a simple directory listing utility.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class Dir
{
    /**
     * The entry point of the application.
     *
     * @param args  The paths to list
     */
    public static void main(String[] args)
    {
        if ((args == null) || (args.length == 0))
        {
            dir(".");
        }
        else
        {
            for (int i=0; i<args.length; i++)
            {
                dir(args[i]);
            }
        }
    }

    /**
     * Print (to standard out) a simple listing of the contents of the
     * given directory.
     *
     * @param path  The path to the directory of interest
     */
    private static void dir(String path)
    {
        File    wd;
        File[]  list;        
        
        wd   = new File(path);
        if (wd.isDirectory())
        {
            list = wd.listFiles();
            System.out.printf("Contents of %s\n", wd.getAbsoluteFile());

            for (int i=0; i<list.length; i++)
            {
                System.out.printf("%-50s %10d\n", 
                                  list[i].getName(), list[i].length());
            }
        }
        else
        {
            System.out.printf("%s is a file.\n", wd.getAbsoluteFile());
        }
        System.out.printf("\n");
    }
}
        
Operating on the File System