面试机试题:扫描D:\demo下的文件夹,当扫描到.txt文件时,运用多线程将该文件名写入该文件里面
package com.demo;
import java.io.*;
public class TestReadFile {
public static void main(String[] args) {
File dir = new File("D:\\demo");
diGui(dir);
System.out.println("执行成功了");
}
private static void diGui(File dir) {
File[] files = dir.listFiles(new MyFileFilter());
if (files != null && files.length != 0) {
for (File file : files) {
if (file.isDirectory()) {
diGui(file);
} else {
MyThread myThread = new MyThread();
myThread.setFile(file);
new Thread(myThread).start();
}
}
}
}
private static class MyFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
}
return pathname.getName().endsWith(".txt");
}
}
private static class MyThread implements Runnable {
private File file;
public void setFile(File file) {
this.file = file;
}
@Override
public void run() {
try {
wirteFile(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void wirteFile(File file) throws IOException {
BufferedWriter bf = null;
try {
bf = new BufferedWriter(new FileWriter(file, true));
bf.write(file.getName());
bf.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
bf.close();
}
}
}