Examples of the File Methods

The following program reads filenames from the command line and returns various information about those files using the methods of the File class.

import java.io.*;


public class FileInfo {


  public static void main(String[] args) {
  
    for (int i = 0; i < args.length; i++) {
      File f = new File(args[i]);
      if (f.exists()) {
        System.out.println("getName: " + f.getName());
        System.out.println("getPath: " + f.getPath());
        System.out.println("getAbsolutePath: " + f.getAbsolutePath());
        try {
          System.out.println("getCanonicalPath: " + f.getCanonicalPath());
        }
        catch (IOException e) {
        }
        System.out.println("getParent: " + f.getParent());
        if (f.canWrite()) System.out.println(f.getName() + " is writable.");
        if (f.canRead()) System.out.println(f.getName() + " is readable.");
        if (f.isFile()) {
           System.out.println(f.getName() + " is a file.");
        }
        else if (f.isDirectory()) {
          System.out.println(f.getName() + " is a directory.");
        }
        else {
          System.out.println("What is this?");
        }
        if (f.isAbsolute()) {
          System.out.println(f.getName() + " is an absolute path.");
        }
        else {
          System.out.println(f.getName() + " is not an absolute path.");
        }
        try {
          System.out.println("Last Modified" + f.lastModified());
          System.out.println(f.getName() + " is " + f.length() + " bytes.");
          System.out.println(f.getName() + " is " + f.length() + " bytes.");
        }
        catch (IOException e) {
        }
      
      }  
      else {
         System.out.println("I'm sorry. I can't find the file " + args[i]);
      }
      
    }
  
  }

}

Previous | Next | Top
Last Modified August 18, 1998
Copyright 1997, 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu