java遍历文件夹_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java遍历文件夹

java遍历文件夹

 2014/4/19 3:43:52  shibin_1109  程序员俱乐部  我要评论(0)
  • 摘要:使用递归:importjava.io.File;importjava.util.ArrayList;publicclassFileSystem1{privatestaticArrayListfilelist=newArrayList();publicstaticvoidmain(String[]args){longa=System.currentTimeMillis();refreshFileList("C:/Users/shibin/Desktop/tupian");System.out
  • 标签:文件 遍历 Java


使用递归
class="java" name="code">
import java.io.File;
import java.util.ArrayList;
public class FileSystem1 {
    private static ArrayList filelist = new ArrayList(); 
    public static void main(String[] args) {
        long a = System.currentTimeMillis();
        refreshFileList("C:/Users/shibin/Desktop/tupian");
        System.out.println(System.currentTimeMillis() - a);
    }
    public static void refreshFileList(String strPath) { 
        File dir = new File(strPath); 
        File[] files = dir.listFiles(); 
        if (files == null) 
            return; 
        for (int i = 0; i < files.length; i++) { 
            if (files[i].isDirectory()) { 
                refreshFileList(files[i].getAbsolutePath()); 
            } else { 
                String strFileName = files[i].getAbsolutePath().toLowerCase();
                System.out.println("---"+strFileName);
                filelist.add(files[i].getAbsolutePath());                    
            } 
        } 
    }
}


不使用递归:
import java.io.File;
import java.util.LinkedList;
public class FileSystem {
    public static void main(String[] args) {
        
        long a = System.currentTimeMillis();
        LinkedList list = new LinkedList();
        File dir = new File("C:/Users/shibin/Desktop/tupian");
        File file[] = dir.listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isDirectory())
                list.add(file[i]);
            else
                System.out.println(file[i].getAbsolutePath());
        }
        File tmp;
        while (!list.isEmpty()) {
            tmp = list.removeFirst();
            if (tmp.isDirectory()) {
                file = tmp.listFiles();
                if (file == null)
                    continue;
                for (int i = 0; i < file.length; i++) {
                    if (file[i].isDirectory())
                        list.add(file[i]);
                    else
                        System.out.println(file[i].getAbsolutePath());
                }
            } else {
                System.out.println(tmp.getAbsolutePath());
            }
        }
        
        System.out.println(System.currentTimeMillis() - a);
    }
}

                     
发表评论
用户名: 匿名