其他分享
首页 > 其他分享> > File汇总

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);
            }
        }

    }
}

标签:File,汇总,System,mth,file,public,Scanner
来源: https://www.cnblogs.com/hellosiyu/p/12489344.html