天天看點

J2ME的檔案系統運用(二)遞歸存儲器目錄

如果我需要列出某個目錄下的所有檔案夾和檔案,那我就需要對這個目錄進行遞歸。對目錄進行遞歸的思想很簡單:每個目錄底下都可能有檔案或者檔案夾,檔案和檔案夾的差別就是名稱否包含”/”,隻要目前的檔案夾下還包含檔案夾我就必須一直周遊下去,遞歸的終點就是遇到檔案或者空檔案夾。遞歸無非就是方法的自調用,找到通用點以及方法的自調用點,結束點,遞歸還是很容易實作的,遞歸本質上是對方法做while循環。

原理很簡單,下面就是代碼部分:

/**
 *
 * @author 水貨程式員
 */
public class FileSystem {

    public Hashtable table = new Hashtable();
    public int level = 1;

        public void getTreeList(String path) {
        try {
            FileConnection fc = (FileConnection) Connector.open(path, Connector.READ);
            Enumeration enums = fc.list();
            Vector folderVector = new Vector();
            while (enums.hasMoreElements()) {
                String name = enums.nextElement().toString();
                //我這裡把name作為key,level作為value,本末倒置,但是讀取資料的時候還是很友善的。
                //這裡我聲明一個level變量,有點參照oracle中level的意思,level用來區分檔案或檔案夾屬于哪一級。
                table.put(name, new Integer(level));
                //判斷是否為檔案夾
                if (name.indexOf("/") > 0) {
                    folderVector.addElement(name);
                }
            }
            int size = folderVector.size();
            //如果沒到最底端
            if (size > 0) {
                level ++;
                for (int i = 0; i < size; i++) {
                    String tmpPath = path + folderVector.elementAt(i).toString();
                    //這裡就是遞歸點
                    getTreeList(tmpPath);
                }
            }else{
                //這裡就是結束點
                return;
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}      

調用代碼也很簡單:

import com.sun.lwuit.Button;
import com.sun.lwuit.Form;
import com.sun.lwuit.layouts.BoxLayout;
import com.thinkrace.UCHome.file.FileSystem;
import java.util.Enumeration;

/**
 *
 * @author 水貨程式員
 */
public class FileListForm extends Form {

    FileSystem fs = new FileSystem();

    public FileListForm() {
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        testFileRecurse();
        show();
    }

    /**
     * 測試檔案遞歸
     */
    public void testFileRecurse() {
        String path = "file:///c:/data/";
        fs.getTreeList(path);
        //由于我的本末倒置,Hashtable中的key存的是檔案或檔案夾的名稱,value存的是級别
        Enumeration enums = fs.table.keys();
        while(enums.hasMoreElements()){
            String name = enums.nextElement().toString();
            Button b = new Button(name);
            addComponent(b);
        }
    }
}      

在這一節裡,我的界面部分并沒有生成相應的樹形結構, 那個level變量的作用就是用來生成樹形結構用的,在下一節我将用LWUIT的Tree實作目錄的樹形結構。