filetraverser/FileTraverser.java
author Markus Bröker <mbroeker@largo.dyndns.tv>
Sun, 24 Oct 2010 20:58:01 +0200
changeset 151 a8c2649cf277
permissions -rw-r--r--
FileTraverser Demo added Proper handling of symlinks in java apps committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * FileTraverser.java
 * Copyright (C) 2010 Markus Broeker
 */

import java.io.File;
import java.util.List;
import java.util.ArrayList;

public class FileTraverser {

    /**
     * @Params folder: the starting directory, the starting folder
     * @Params recursive: list subfolders recursively or not
     * @Params list: the list to store the data
     */
    public static void find(String folder, boolean recursive, List<String> list) {

        File directory = new File (folder);
        if (!directory.isDirectory())
            return;
        else
            list.add(directory.getPath());

        /* prevent linux recursion problems when using symlinks */
        if (Unix.isLink(folder)) {
            return;
        }

        File[] files = directory.listFiles();

        for (File f : files) {
            if (f.isDirectory() && recursive) {
                find(f.getPath(), recursive, list);
            } else
                list.add(f.getPath());
        }
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        String homeDir = System.getProperty("user.home");
        boolean recursive = false;

        if (args.length == 2) {
            homeDir = args[0];
            recursive = Integer.parseInt(args[1]) != 0 ? true : false;
        }

        find(homeDir, recursive, list);
        for (String s : list) {
            System.out.println ("List: " + s);
        }
    }
}