Determining if a Filename Path is a File or Directory


File testPath = new File("directoryName"); boolean isDir = testPath.isDirectory(); if (isDir) {    // testPath is a directory } else {    // testPath is a file }



In this phrase, we determine if a given File object represents a file or a directory. The isDirectory() method of the File class will return true if the File object on which it is called represents a directory, and it will return false if the File object represents a file.

This method is useful when you want to write a method that will traverse all of the files and directories under a given directory. Perhaps you want to write a method that will list all of the files under a specified directory and you want the method to recurse into all the subdirectories contained within the specified directory. As you step through each listing contained in a directory, you would use the isDirectory() method to determine if the listing represents a file or a directory. Below is an example of such a method that makes use of the isDirectory() method:

static void listAllFiles(File dir) {    String[] files = dir.list();    for (int i = 0; i < files.length; i++) {       File f = new File(dir, files[i]);       if (f.isDirectory()) {          listAllFiles(f);       }       else {          System.out.println(f.getAbsolutePath());       }    } }


If you call this method and pass in a File object representing a directory, it will print the full-path names of all files contained within that directory and all of its subdirectories.

There is also an isFile() method on the File class that will return true if the File object on which it is called represents a file, otherwise it will return false.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net