List all file names in the directory recursively, relative to the starting directory. - Java java.io

Java examples for java.io:File Name

Description

List all file names in the directory recursively, relative to the starting directory.

Demo Code

/**//from  w  ww  . ja  v  a  2  s.c  o  m
 * This file is part of the CRISTAL-iSE kernel.
 * Copyright (c) 2001-2014 The CRISTAL Consortium. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
 *
 * http://www.fsf.org/licensing/licenses/lgpl.html
 */
 
import java.io.File;
import java.util.ArrayList;

public class Main {
  public static void main(String[] argv) {
    String dirPath = "java2s.com";
    boolean withDirs = true;
    boolean recursive = true;
    System.out.println(listDir(dirPath, withDirs, recursive));
  }

  /**************************************************************************
   * List all file names in the directory recursively, relative to the starting
   * directory.
   *
   * @param dirPath
   *          starting directory
   * @param recursive
   *          goes into the subdirectories
   **************************************************************************/
  static public ArrayList<String> listDir(String dirPath, boolean withDirs, boolean recursive) {
    ArrayList<String> fileNames = new ArrayList<String>();
    File dir = new File(dirPath);
    File files[];
    String fileName;

    if (!checkDir(dirPath)) {
      return null;
    }

    files = dir.listFiles();

    for (File file : files) {
      fileName = file.getName();

      if (file.isFile()) {
        fileNames.add(dirPath + "/" + fileName);
      } else {
        if (recursive)
          fileNames.addAll(listDir(dirPath + "/" + fileName, withDirs, recursive));

        if (withDirs)
          fileNames.add(dirPath + "/" + fileName);
      }
    }

    return fileNames;
  }

  /**************************************************************************
   * checks for existing directory
   **************************************************************************/
  static public boolean checkDir(String dirPath) {
    File dir = new File(dirPath);

    if (dir.isFile()) {
      return false;
    } else if (!dir.exists()) {
      return false;
    }

    return true;
  }
}

Related Tutorials