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);
}
}
}
}
我对任何唾手而得,快速,出自本能,即兴,含混的事物没有信心。我相信缓慢,平和,细水长流的力量,踏实,冷静。我不相信缺乏自律精神和不自我建设,不努力,可以得到个人或集体的解放。