日期:2014-05-20 浏览次数:20827 次
import java.io.*; public class Demo01 { public static void main(String... args) { //D:\document\java\JAVASE File f = new File("D:"+File.separator+"document"+ File.separator+"java"+File.separator+"JAVASE"); fun(f); } public static void fun(File name) { File[] farr = name.listFiles(); for(int i = 0; i < farr.length;i++) { if(farr[i].isDirectory()) { System.out.println(farr[i].getName()+"目录下:"); fun(farr[i]); System.out.println(""); } else { System.out.println(farr[i].getName()); } } } }
------解决方案--------------------
第一个是递归的,第二个是非递归的。
import java.io.*; import java.util.*; public class ListFileRecursion{ public static void listFile(String filePath){ File file = new File(filePath); if(file.exists()){ if(file.isDirectory()){ System.out.print("Folder: "+ file.toString()); File[] fileArray = file.listFiles(); System.out.println(" includes "+ fileArray.length +" files/folders directly."); for(File subFile : fileArray){ listFile(subFile.toString()); } } else{ System.out.println(file.toString()); } } else{ System.err.print("The file/folder doesn't exist!"); } } public static void main(String args[]){ listFile("C:\\VM_Image"); } } 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/justinavril/archive/2008/09/20/2955991.aspx