Thursday, 24th June 2010
The new frontier for learning Java

FileIterator.java

From WikiJava

Jump to: navigation, search


Recursion is the process of calling a method from within itself so as to repeat a block of code repeatedly.

Contents

the article

This application demostrates recursion and woking with files. The application searches for directories and files within a given path and prints the name and size of each file and directory, and the user can specify wether or not the program should print both files and directories or just directories.

We accomplish this by creating three classes which are;

1. IsDirectory.java:- This class implements the FileFilter interface and it searches for directories in a specified path.

2. IsNotDirectory.java:- This class implements the FileFilter interface and it searches for files in each directory.

3. FileIterator.java:- This is the class with the main method and references the first two classes and prints out the directories and files.

IsDirectory.java

package org.wikijava.recursion;
 
import java.io.*;
 
/**
 * @author Alex Mutuku Mbolonzi
 * @version 01/07/08
 */
public class IsDirectory implements java.io.FileFilter {
 
    /**
     * accept the pathname and search for diretories. return true if a directory
     * is found
     */
    public boolean accept(File f) {
	return f.isDirectory();
    }
}

IsNotDirectory.java

package org.apache.commons.jci.examples.commandline;
 
import java.io.*;
 
/**
 * @author Alex Mutuku Mbolonzi
 * @version 01/07/08
 */
public class IsNotDirectory implements java.io.FileFilter {
    /*
     *  return true if a file is found
     */
    public boolean accept(File f) {
	return f.isFile();
    }
}

FileIterator.java

package org.wikijava.recursion;
 
import java.io.*;
 
/**
 * @author Alex Mutuku Mbolonzi
 * @version 30/06/08
 */
public class FileIterator {
    // stores the number of files in each directory.
    int countFiles = 0;
 
    // stores the size of each directory.
    int dirSize = 0;
 
    // declare a string.
    static String p = "";
 
    static String fileName;
 
    /**
     * prints out contents in each diretory.
     * 
     * @param folder
     */
    public void printContents(File folder) {
 
	// creates an array of directorys objects
	File[] directorys = folder.listFiles(new IsDirectory());
 
	// print out all objects in the array.
	for (int i = 0; i < directorys.length; i++) {
 
	    // get the name of each directory and print.
	    System.out.print(directorys[i].getName() + " ");
 
	    // print contents of directory.
	    printContents(directorys[i]);
	}
 
	// creates an array of files objects
	File[] files = folder.listFiles(new IsNotDirectory());
 
	// loops through the array
	for (int z = 0; z < files.length; z++) {
	    // get the size of each file.
	    files[z].length();
	    // count the files in a directory
	    countFiles = z;
	    // sum the size of all files in a diectory
	    dirSize += files[z].length();
	}
 
	// print out the number of files and size of directory.
	System.out.println("[ " + (countFiles + 1) + " files]"
		+ "[ Directory Size " + (dirSize / 10526760) + " MB ]");
 
	// prints out all objects in the array.
	for (int k = 0; k < files.length; k++) {
 
	    // get the name and size of each file and print
	    System.out.println("\t" + files[k].getName() + "  [ "
		    + files[k].length() + " bytes ]");
	}
 
	System.out.println();
 
    }
 
    public static void main(String[] args) throws IOException {
 
	try {
 
	    // declare a new BufferedReader object.
	    BufferedReader printFiles = new BufferedReader(
		    new InputStreamReader(System.in));
 
	    // prompt user to enter thier preference.
	    System.out.print("Would you like to print "
		    + "out files and directories (Y/N)? ");
 
	    // convert input to upper case.
	    p = printFiles.readLine().toUpperCase();
	    // creates a new object of the pathname.
	    File rootFolder = new File("D:/music");
	    // creates a new FileIterator Object.
	    FileIterator fi = new FileIterator();
	    // print contents of root folder.
	    fi.printContents(rootFolder);
 
	    if (p == null) {
 
		throw new IOException("string p is null");
	    }
	}
 
	catch (IOException e) {
 
	    System.out.println("You have not specified wether the "
		    + "program should print files and "
		    + "directories or just directories!");
	}
    }
}


Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page

choice

what happens if one enters a char 'N' for no or 'Y' for yes. could u prints directories names alone.otherwise well done. Regards Machot, Sudan

--66.178.108.182 11:31, 28 November 2008 (UTC)


normalizing the example

I think there are several things to change in this example:

  1. I don't like the fact it's interactive, it would be way better if there was an option at command line.
  2. the interactivity is even not used, to answer to 66.178.108.182 this program doesn't seem to consider the 'Y' or 'N' at all, just type anything to avoid the exception
  3. the exception is thrown upon an user input, it's pretty common that the user would make a mistake there so it would be better to consider such a case in an if statement, rather than in a try catch.

I quickly updated the example formatting the lines. it's important not to write lines longer than 80 characters. To do so I simply copy pasted the code in eclipse and pressed CTRL + F (format code).

--DonGiulio 12:49, 28 November 2008 (UTC)


Title (required):

Website:

Comment: