File汇总

1 目录的遍历

import java.io.File;

public class test {
    public static void main(String[] args) {
        String path = "/Users/mima000000/Desktop/xc";
        File file  = new File(path);
        String[] list = file.list();
        for (int i = 0; i < list.length; i++) {
            System.out.println(list[i]);
        }
    }
}

2 递归累加求和,求1到100的和

import java.io.File;
import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        System.out.println(" 请输入一个数字");
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int res = mth(num);
        System.out.println(res);


    }
    public static int  mth(int num){
        if(num==1){
            return 1 ;
        }
        return num+mth(num-1);

    }
}

3 递归打印多级目录

import java.io.File;
import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        System.out.println("请输入目录:");
        Scanner sc = new Scanner(System.in);
        String path = sc.next();
        File file = new File(path);
        mth(file);


    }
    public static void  mth(File file){
        File[] files = file.listFiles();
        for (File f:files
             ) {
            if (f.isFile()){
                System.out.println(f.getName());
            }else {
                mth(f);
            }
        }

    }
}

4 递归打印,同时根据规则过滤

import java.io.File;
import java.io.FileFilter;
import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        System.out.println("请输入目录:");
        Scanner sc = new Scanner(System.in);
        String path = sc.next();
        File file = new File(path);
        mth(file);


    }
    public static void  mth(File file){
        File[] files = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(".jpg") || pathname.isDirectory();
            }
        });


        for (File f:files
             ) {
            if (f.isFile()){
                System.out.println(f.getName());
            }else {
                mth(f);
            }
        }

    }
}

posted @ 2020-03-13 21:58  姚狗蛋  阅读(78)  评论(0编辑  收藏  举报