List Files And Directories
Recursivesly lists files and directories and prints them as a tree structure.
import java.io.*; import java.util.*; /** * Ynori7 * 9.26.07 */ public class Tree { ArrayList<String> filelist = new ArrayList<String>(); public Tree() { String a = "C:\\"; //change this to whatever directory you wanna search int counter = -1; recur(a, counter); SaveFile(); } private void recur(String a, int counter) { File dir = new File(a); //opens the specified directory counter++; if(dir.exists()) //checks to see if the specified path is acceptable { String[] files = dir.list(); for(int i=0; i< files.length; i++) { String c=""; for(int x=0; x< counter; x++) { c+=" ";} //tabs in to show that stuff is inside a folder filelist.add(c+files[i]); System.out.println(c+files[i]); String b = a+"\\"+files[i]; try{ recur(b, counter); }catch(Exception e){} //makes sure you're opening a folder, not a file } } else{ System.out.println("Folder not found"); } } //save data to a text file private void SaveFile() { try { //both file and print writer needed. fileID is the name of the file. FileWriter fileID = new FileWriter ("FileListSave.txt"); PrintWriter outFile = new PrintWriter(fileID); for(int x = 0; x<filelist.size(); x++) { outFile.println( filelist.get(x) ); } outFile.close(); } catch (IOException io) { System.out.println(""); System.out.println("---Error writing to the data file -"+ io.getMessage()+"---"); } System.exit(0); } public static void main(String[] args) { new Tree(); } }

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Download this code in plain text format here