This is a written test question. I don’t know how to write it for a while. In the final analysis, the basics are still not enough, and I have to work hard.
First, judge whether it is a directory or a file, and if the directory contains a string by searching all files in the directory.
public class Test{
public static void search(File file, String str) throws FileNotFoundException{
Scanner scanner = new Scanner(a,"gbk");//文件编码,可以改成utf-8格式
int k = 0;
while(true){
if(scanner.hasNext()==false)
break;
String s = scanner.nextLine();
k++;
if(s.contains(x)){
String a = "文件"+file.getName+"第"+k+"行内容:"+s;
System.out.println(a);
}
}
}
public static void isFileorDirectory(File file, String str) throws FileNotFoundException{
if(!file.isDirectory()){//判断是否文件
search(file,str);
}
File[] fileNum = file.listFiles();
if(fileNum==null)
return;
for(File file1: fileNum){
if(file1.isFile()){
search(file1, str);//是文件,直接查找
}
if(file1.isDirectory()){//是目录,则对其目录下的目录或文件继续查找
isFileorDirectory(file1,str);
}
}
}
public static void main(String[] args){
isFileorDirectory(new File("目录或者文件名","字符串");
}
}