import java.io.File; import java.util.Arrays; import java.util.Scanner; import java.io.IOException; /** Demo.java - simple experiment with files and directories. * What can we use in java.io.File? * I had originally wanted to call this program File.java, but I can't * because I include a class called File. Oh well, I'll just call it Demo. * File's getCanonicalPath() may throw an IOException. */ public class Demo { public static void main(String [] args) throws IOException { // Ask the user for a directory Scanner kbd = new Scanner(System.in); System.out.printf("Enter name of a directory: "); String name = kbd.nextLine(); File inputFile = new File(name); String [] fileList = inputFile.list(); if (fileList == null) { System.out.printf("Error: file list is null. Not a directory.\n"); System.exit(1); } Arrays.sort(fileList); System.out.printf("This directory has %d files.\n", fileList.length); long totalLength = 0; for (int i = 0; i < fileList.length; ++i) { System.out.printf("For the file %s:\n", fileList[i]); // Using a File object, look up statistics. String pathName = inputFile + "/" + fileList[i]; File f = new File(pathName); System.out.println(" canRead() returns " + f.canRead()); System.out.println(" canWrite() returns " + f.canWrite()); System.out.println(" canExecute() returns " + f.canExecute()); System.out.println(" getFreeSpace() returns " + f.getFreeSpace()); System.out.println(" getTotalSpace() returns " + f.getTotalSpace()); System.out.println(" getUsableSpace() returns " + f.getUsableSpace()); System.out.println(" isDirectory() returns " + f.isDirectory()); System.out.println(" isFile() returns " + f.isFile()); System.out.println(" lastModified() returns " + f.lastModified()); System.out.println(" length() returns " + f.length()); System.out.println(" getAbolutePath() returns " + f.getAbsolutePath()); System.out.println(" getCanonicalPath() returns " + f.getCanonicalPath()); totalLength += f.length(); } System.out.printf("The total size of all files is %d bytes.\n", totalLength); } }