1.从文件中查找匹配的字符串
/**
* @param path
* 路径
* @param str
* 匹配字符串
* @return
* @throws IOException
*/
public static int find(String path, String str) throws IOException {
File file = new File(path);
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String r = bufferedReader.readLine();
int count = 0;
while (r != null) {
//取得第一次匹配索引的位置
int index = r.indexOf(str);
while (true) {
if (index >= 0) {
count++;
} else {
break;
}
//从第一匹配索引的位置进行搜索
index = r.indexOf(str, index + 1);
}
r = bufferedReader.readLine();
}
return count;
}
2.列出目录下的所有文件
/**
* 列出目录下的文件
* @param path
*/
public static void fileList(String path){
File file = new File(path);
//判定是否为目录
if(file.isDirectory()){
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getName());
}
}
}
3.列出目录下的所有子目录以及子目录下的子目录(递归)
/**
* 列出目录下的所有子目录以及子目录下的子目录
* @param path
*/
public static void directoryList(String path){
File file = new File(path);
if (file.isDirectory()) {
//过滤非目录文件
File[] files = file.listFiles(new FileFilter(){
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
}else {
return false;
}
}
});
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getAbsolutePath());
//递归列出所有目录
directoryList(files[i].getAbsolutePath());
}
}
}