Files and File Systems in Java
An Introduction |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
File
and Files
Classes:
File
object is an encapsulation of
a file/directory handle (not an actual
file on the file system)Files
class is a utility class for operating
on File
and Path
objectsFile
Object:
File
ObjectsFile
Objects (cont.)File.mkdir()
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"); } }