关于IO及正则的结合使用
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class DirList {
public static void main(String[] args) throws Exception {
File path = new File( ". ");
String[] list;
if (args.length == 0)
list = path.list();
else
list = path.list(new DirFilter(args[0]));
Arrays.sort(list);
for (int i = 0; i < list.length; i++)
System.out.println(list[i]);
System.out.println(path.getAbsolutePath());
System.out.println(path.getCanonicalPath());
}
}
class DirFilter implements FilenameFilter {
private Pattern pattern;
public DirFilter(String regex) {
pattern = Pattern.compile(regex);
}
public boolean accept(File dir, String name) {
// Strip path information, search for regex:
return pattern.matcher(new File(name).getName()).matches;
}
}
这是要求根据命令行输入的正则表达式查找相应的文件,并打印出来,我想修改一下,
使得如果查找到了子文件夹,就将子文件夹下的内容也列出来,如果子文件夹下还有子文件夹,就再把里面的内容打印出来,一直下去,直到没有子文件夹为止
------解决方案--------------------public void list(String aFilePath){
File file = new File(aFilePath);
if(file.isFile()){
System.out.println( "This is a file: " + file.getAbsolutePath());
}else{
list(file);
}
}
public void list(File aFile){
File[] subFiles = aFile.listFiles();
for(int i=0; i <subFiles.length; i++){
if(subFiles[i].isFile()){
System.out.println( "This is a file: " + subFiles[i].getAbsolutePath());
}else{
list(subFiles[i]);
}
}
}
------解决方案--------------------你可以把主函数中的代码提出来写一个方法,如
//path表示文件的路径,改成字符串也行,
//regex表示你输入的正则
public void recursiveFile(File path, String regex) {
File[] files = path.listFiles(new DirFilter(regex));
for (int i = 0; i < files.length; i++) {
System.out.println( "file "+files[i]);
}
File file[] = path.listFiles();
for (int k = 0; k < file.length; k++) {
if (file[k].isDirectory()) {
recursiveFile(file[k], regex);
}
}
}
把accept(File dir, String name)方法修改下
public boolean accept(File dir, String name) {
File file = new File(dir+ "/ "+name);
if(file.isDirectory()){
return false;
}
return pattern.matcher(file.getName()).matches;
}
试试看行不行,没有试过