java遍曆目錄二種方法

來源:互聯網
上載者:User

我是通過分割字串來求得其所有子目錄相對於根目錄的深度,然後再減去輸入目錄相對於根目錄的深度,就得到了輸入目錄的深度

方法一

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:java");
        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());                   
            }
        }
    }
}


方法二

public static void printdirectory(file f,int depth){
  if(!f.isdirectory()){//如果不是目錄,則列印輸出
   system.out.println(gettap(depth)+f.getname());
  }else{
   file[] fs=f.listfiles();
   system.out.println(gettap(depth)+f.getname());
   depth++;
   for(int i=0;i<fs.length;++i){
    file file=fs[i];
    printdirectory(file,depth);
   }
  }
}


其中gettap方法是輔助方法,目的是使輸出具有一定的層次關係,方法定義如下:

private static string gettap(int depth){
  stringbuffer tap=new stringbuffer();
  for(int i=0;i<depth;i++){
   tap.append("------");
  }
  return tap.tostring();
}


 

public static void main(string[] args){
  file f=new file("test");
  printdirectory(f,0);
}


test
------11
------------111
------------------1111.txt
------------------1112.txt
------------112.txt
------12
------------123.txt
------13.txt

總結問題

問題一:java中遍曆目錄時,總是轉化成檔案數組,但是如果目錄下檔案超過10萬個,這時就容易死機?有沒有更好的辦法,聽說c++提供了更好的辦法,java中我沒找到?

 

問題二:,java中,能不能遍曆目錄下特定類型的檔案??比如我只遍曆 *.jpg的檔案。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.