使用递归遍历目录并打印输出在控制台
import java.io.File;
public class BianLiFile {
public static void main(String[] args) {
File file = new File("D:\\");
long begin = System.currentTimeMillis();
bianLiFile(file);
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - begin) / 1000 + "秒");
}
public static void bianLiFile(File file) {
File[] files = file.listFiles();
if (files != null) {
for (File file1 : files) {
if (file1.isFile()) {
System.out.println(file1.getAbsolutePath());
} else {
bianLiFile(file1);
}
}
}
}
}
使用递归遍历目录并打印符合后缀格式的文件在控制台
第一种
import java.io.*;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
File f = new File("D:\\百度云");
ArrayList<File> list = new ArrayList<>();
getLuJing(f, list);
System.out.println(list);
System.out.println("共有" + list.size() + "个文件符合条件");
}
public static void getLuJing(File file, ArrayList<File> list) {
File[] files = file.listFiles();
if (files != null) {
for (File file1 : files) {
if (file1.isDirectory()) {
getLuJing(file1, list);
} else {
// if (file1.getAbsolutePath().endsWith(".avi"))
if (file1.getAbsolutePath().endsWith(".mkv"))
list.add(file1);
}
}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream("G:\\桌面\\百度云mkv格式文件.txt");
//把结果写出到txt文本里,没错!我的桌面就是G盘
for (File file9 : list) {
String absolutePath = file9.getAbsolutePath() + "\r\n";
byte[] bytes = absolutePath.getBytes();
fos.write(bytes);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
第二种
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test1 {
public static void main(String[] args) throws FileNotFoundException {
File f = new File("D:\\百度云");
FileOutputStream fos = new FileOutputStream("G:\\桌面\\D盘百度云.txt");
try {
getLuJing(f, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void getLuJing(File file, FileOutputStream fos) throws IOException {
File[] files = file.listFiles();
if (files != null) {
for (File file1 : files) {
if (file1.isDirectory()) {
getLuJing(file1, fos);
} else {
if (file1.getAbsolutePath().endsWith(".mkv")) {
System.out.println(file1);
String absolutePath = file1.getAbsolutePath() + "\r\n";
fos.write(absolutePath.getBytes());
}
}
}
}
}
}