我正在尝试从根目录和根目录内的子目录获取数组中的文件列表。将 C:\
视为我的根目录。我还想根据特定的文件名模式获取 C:\abc
和 C:\def
列表。这是我尝试过的代码。
public String[] getFilesList(File path){
String[] filesList = null;
final String[] directories = null;
try {
properties.load(new StoricoPV_ISAU().getFile());
} catch (IOException e) {
log.error(e.getMessage());
e.printStackTrace();
}
filesList = path.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
if(name.matches(Constants.INTERNA_REGEX)){
return true;
}else if(name.matches(Constants.SISS_REGEX)){
return true;
}else if(new File(properties.getProperty(Constants.PATH_NAME)+name).isDirectory()){
//error here: The final local variable directories cannot be assigned, since it is defined in an enclosing type
directories = new File(properties.getProperty(Constants.PATH_NAME)).list(new FilenameFilter() {
public boolean accept(File dir, String name) {
if(name.matches(Constants.INTERNA_REGEX)){
return true;
}else if(name.matches(Constants.SISS_REGEX)){
return true;
}else{
log.info("Invalid file or directory: "+name);
return false;
}
}
});
return false;
}
return false;
}
});
return filesList;
}
好吧,我知道变量 directories
不能是 final
但同时,它需要是 final
才能在内部工作这个方法。我如何修改我的逻辑,以便最终 C:\
、C:\abc
和 C:\def
中的所有文件的列表是根据我指定的文件模式,所有内容都在变量 filesList
中返回。对此的任何帮助将不胜感激。
注意:我不需要超出目录的 1 级深度。例如,我们必须忽略目录中的任何目录 C:\abc
最佳答案
我首先想到的是递归。因为您只需要级别文件夹,所以我添加一个变量来控制它,以防需求发生变化。
public String[] getFilesList(File path) {
int deepth = 1; // Control the deepth of recursion
List<String> list = new ArrayList<String>();
getFilesList(path, list, deepth);
return list.toArray(new String[list.size()]);
}
public void getFilesList(File path, final List<String> list, int deepth) {
if (deepth >= 0) {
final int newDeepth = deepth - 1;
String[] subList = path.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
File subFile = new File(dir.getAbsolutePath() + "/" + name);
if (subFile.isFile()) {
if (name.matches(Constants.INTERNA_REGEX)) {
return true;
} else if (name.matches(Constants.SISS_REGEX)) {
return true;
} else {
// log.info("Invalid file or directory: " + name);
return false;
}
} else {
getFilesList(subFile, list, newDeepth);
}
return false;
}
});
list.addAll(Arrays.asList(subList));
}
}
关于java - 嵌套accept()以获取一个字符串数组中子目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36543516/