ハードディスク(HDD)のキーを含むファイルを検索
1499 ワード
package com.sxt.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Scan {
public static void main(String[] args) {
long start = System.currentTimeMillis();
searchBuffer(new File("e:/ "), " ", 1024*1024*2);
System.out.println(" :" + (System.currentTimeMillis() - start) + "ms");
}
/**
* keyword , 。
* , keyword keyword 。
* @param file
* @param keyword
* @param bufferSize
*/
public static void searchBuffer(File file, String keyword, int bufferSize) {
if (file.isFile()) {
if(file.getName().contains(keyword.trim())) {
System.out.println(file.getPath());
} else {
BufferedReader in = null;
try {
try {
in = new BufferedReader(new FileReader(file), bufferSize);
String line = "";
while ((line = in.readLine()) != null) {
if (line.contains(keyword.trim())) {
System.err.println(file.getPath());
break;
}
}
} finally {
if (in != null) {
in.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
File[] filenames = file.listFiles();
if (filenames == null) {
return;
}
for (File f : filenames) {
searchBuffer(f, keyword, bufferSize);
}
}
}
}