java 和 android 文件管理器(遞歸算法)

[java] 
import java.io.File; 
import java.io.IOException; 
import java.util.Scanner; 
 
 
public class Folder { 
 
    public static void main(String[] args) { 
        // TODO Auto-generated method stub 
 
        Folder folder = new Folder(); 
        Scanner sc = new Scanner(System.in); 
        String flag = sc.nextLine(); 
        flag = flag.trim(); 
        try{ 
        flag = flag.substring(11,flag.length()); 
        }catch(Exception e){ 
            e.printStackTrace(); 
            folder.traverseDirectory("."); 
            return; 
        } 
        flag = flag.trim(); 
        String flag1 = flag.substring(0, 3); 
        System.out.println("flag"+flag); 
        String file = flag.substring(3,flag.length()).trim(); 
        System.out.println("判斷標志"+flag1); 
        if(flag1.equals("add")){ 
                File file1 = new File(file); 
                System.out.println("進入add"); 
                System.out.println("創建目錄"); 
                file1.mkdir(); 
                folder.traverseDirectory("."); 
        }else if(flag1.equals("del")){ 
            System.out.println("執del"); 
            File file2 = new File(file); 
            file2.delete(); 
            folder.traverseDirectory("."); 
        }else if(flag1!=""){ 
            System.out.println("瀏覽指定目錄"); 
            try{ 
            folder.traverseDirectory(file); 
            }catch(Exception e){ 
                System.out.println("輸入路徑不對"); 
            } 
        } 
         
    } 
     
    static int blank = 0; 
    public void traverseDirectory(String name){ 
        blank++; 
        File directory = new File(name); 
        File back[] = directory.listFiles(); 
        for(int j=0;j<back.length;j++){ 
            if(back[j].isFile()){ 
                for(int i=0;i<blank;i++){ 
                    System.out.print("–"); 
                } 
                System.out.println(back[j].getName()); 
            } 
        } 
        for(int i=0;i<back.length;i++){ 
            if(back[i].isDirectory()){ 
                for(int j=0;j<blank;j++){ 
                    System.out.print("–"); 
                } 
                System.out.println(back[i].getName()); 
                traverseDirectory(back[i].getAbsolutePath()); 
                blank–; 
            } 
        } 
    } 

java和android都可以用的文件管理器,可以實現添加刪除目錄,查看指定目錄的文件,而且是目錄樹的形式,看起來非常清晰。

文件管理器應用非常廣泛,殺毒軟件,收集信息,好多功能可以擴展。本程序最重要的是遞歸算法,如有疑問請留言。

You May Also Like