DirectoryTree.java 8.6 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
 *
 */

/** Encapsulates a notion of a directory tree. Designed to allow fast
    querying of full paths for unique filenames in the hierarchy. */

import java.io.*;
import java.util.*;

public class DirectoryTree {

    /** The root of the read directoryTree */
    private Node rootNode;

    /** Subdirs to ignore; Vector of Strings */
    private Vector subdirsToIgnore;

    /** This maps file names to Lists of nodes. */
    private Hashtable nameToNodeListTable;

    /** Output "."'s as directories are read. Defaults to false. */
    private boolean verbose;

    public DirectoryTree() {
        subdirsToIgnore = new Vector();
        verbose = false;
    }

50 51 52 53 54 55 56 57
    public void addSubdirToIgnore(String subdir) {
        subdirsToIgnore.add(subdir);
    }

    private class FileIterator implements Iterator {
        private Vector nodes = new Vector();

        public FileIterator(Node rootNode) {
58 59 60
            if(rootNode == null) {
                return;
            }
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
            nodes.add(rootNode);
            prune();
        }
        public boolean hasNext() {
            return nodes.size() > 0;
        }
        public Object next() {
            Node last = (Node)nodes.remove(nodes.size() - 1);
            prune();
            return new File(last.getName());
        }

        public void remove() {
            throw new RuntimeException();
        }
D
duke 已提交
76

77 78 79 80 81 82 83 84 85 86 87 88 89
        private void prune() {
            while (nodes.size() > 0) {
                Node last = (Node)nodes.get(nodes.size() - 1);

                if (last.isDirectory()) {
                    nodes.remove(nodes.size() - 1);
                    nodes.addAll(last.children);
                } else {
                    // Is at file
                    return;
                }
            }
        }
D
duke 已提交
90 91
    }

92 93
    public Iterator getFileIterator() {
        return new FileIterator(rootNode);
D
duke 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    }

    /** Output "."'s to System.out as directories are read. Defaults
        to false. */
    public void setVerbose(boolean newValue) {
        verbose = newValue;
    }

    public boolean getVerbose() {
        return verbose;
    }

    public String getRootNodeName() {
        return rootNode.getName();
    }

    /** Takes an absolute path to the root directory of this
        DirectoryTree. Throws IllegalArgumentException if the given
        string represents a plain file or nonexistent directory. */

    public void readDirectory(String baseDirectory)
        throws IllegalArgumentException {
116
        File root = new File(Util.normalize(baseDirectory));
D
duke 已提交
117
        if (!root.isDirectory()) {
118
            return;
D
duke 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
        }
        try {
            root = root.getCanonicalFile();
        }
        catch (IOException e) {
            throw new RuntimeException(e.toString());
        }
        rootNode = new Node(root);
        readDirectory(rootNode, root);
    }

    /** Queries the DirectoryTree for a file or directory name. Takes
        only the name of the file or directory itself (i.e., no parent
        directory information should be in the passed name). Returns a
        List of DirectoryTreeNodes specifying the full paths of all of
        the files or directories of this name in the DirectoryTree.
        Returns null if the directory tree has not been read from disk
        yet or if the file was not found in the tree. */
    public List findFile(String name) {
        if (rootNode == null) {
            return null;
        }

        if (nameToNodeListTable == null) {
            nameToNodeListTable = new Hashtable();
            try {
                buildNameToNodeListTable(rootNode);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        return (List) nameToNodeListTable.get(name);
    }

    private void buildNameToNodeListTable(Node curNode)
      throws IOException {
        String fullName = curNode.getName();
        String parent = curNode.getParent();
        String separator = System.getProperty("file.separator");

        if (parent != null) {
          if (!fullName.startsWith(parent)) {
            throw new RuntimeException(
                "Internal error: parent of file name \"" + fullName +
                "\" does not match file name \"" + parent + "\""
            );
          }

          int len = parent.length();
          if (!parent.endsWith(separator)) {
            len += separator.length();
          }

          String fileName = fullName.substring(len);

          if (fileName == null) {
            throw new RuntimeException(
                "Internal error: file name was empty"
            );
          }

          List nodeList = (List) nameToNodeListTable.get(fileName);
          if (nodeList == null) {
            nodeList = new Vector();
            nameToNodeListTable.put(fileName, nodeList);
          }

          nodeList.add(curNode);
        } else {
          if (curNode != rootNode) {
            throw new RuntimeException(
                "Internal error: parent of file + \"" + fullName + "\"" +
                " was null"
            );
          }
        }

        if (curNode.isDirectory()) {
          Iterator iter = curNode.getChildren();
          if (iter != null) {
            while (iter.hasNext()) {
              buildNameToNodeListTable((Node) iter.next());
            }
          }
        }
    }

    /** Reads all of the files in the given directory and adds them as
        children of the directory tree node. Requires that the passed
        node represents a directory. */

    private void readDirectory(Node parentNode, File parentDir) {
        File[] children = parentDir.listFiles();
        if (children == null)
            return;
        if (verbose) {
            System.out.print(".");
            System.out.flush();
        }
        for (int i = 0; i < children.length; i++) {
            File child = children[i];
            children[i] = null;
            boolean isDir = child.isDirectory();
            boolean mustSkip = false;
            if (isDir) {
                for (Iterator iter = subdirsToIgnore.iterator();
                     iter.hasNext(); ) {
                    if (child.getName().equals((String) iter.next())) {
                        mustSkip = true;
                        break;
                    }
                }
            }
            if (!mustSkip) {
                Node childNode = new Node(child);
                parentNode.addChild(childNode);
                if (isDir) {
                    readDirectory(childNode, child);
                }
            }
        }
    }

    private class Node implements DirectoryTreeNode {
        private File file;
        private Vector children;

        /** file must be a canonical file */
        Node(File file) {
            this.file = file;
            children = new Vector();
        }

        public boolean isFile() {
            return file.isFile();
        }

        public boolean isDirectory() {
            return file.isDirectory();
        }

        public String getName() {
            return file.getPath();
        }

        public String getParent() {
            return file.getParent();
        }

        public void addChild(Node n) {
            children.add(n);
        }

        public Iterator getChildren() throws IllegalArgumentException {
            return children.iterator();
        }

        public int getNumChildren() throws IllegalArgumentException {
            return children.size();
        }

        public DirectoryTreeNode getChild(int i)
            throws IllegalArgumentException, ArrayIndexOutOfBoundsException {
            return (DirectoryTreeNode) children.get(i);
        }
    }
}