Java下的File类(文件类,其实感觉文件类有点误导性,用“文件路径”会好一点)有list方法,会返回指定路径下所有文件和目录,用这个方法以及简单的递归可以写出一个简陋的文件遍历程序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import java.io.File; import java.io.FileWriter; import java.io.IOException;
public class test_for_team_study_2 { public static void traverse(String name, FileWriter wt) throws IOException { wt.write(name + "\r\n"); File path = new File(name); String[] list = path.list(); if( null == list ) return ; for(int i = 0; i < list.length; i ++) if( -1 == list[i].indexOf(".") ) traverse(name + "/" + list[i], wt); } public static void main(String[] args) throws IOException { FileWriter wt = new FileWriter("C:/Users/Administrator/Desktop/file in D.out"); String name = "D:/"; File path = new File(name); String[] list = path.list(); for(int i = 0; i < list.length; i ++) { wt.write("now is the file#:" + i + "\r\n==========================\r\n"); traverse(name + "/" + list[i], wt); wt.write("\r\n\r\n\r\n"); } wt.flush(); wt.close(); System.out.println("finished!"); } }
|