当我执行这段代码时,我遇到了这个奇怪的问题:
cdrFiles = dir.list(filter);
System.out.println("cdrFiles length: " + cdrFiles.length);
if (cdrFiles.length >= 1) {
System.out.println("there is 1 or more files");
}else{
throw new IOException("1No files in dir: " + directory + " that match the correct pattern");
}
此处的目录包含 1 个与过滤器匹配的文件。
输出是:
cdrFiles length: 0
java.io.IOException: 1No files in dir: cdrs that match the correct pattern
当我评论异常时:
cdrFiles = dir.list(filter);
System.out.println("cdrFiles length: " + cdrFiles.length);
if (cdrFiles.length >= 1) {
System.out.println("there is 1 or more files");
}else{
//throw new IOException("1No files in dir: " + directory + " that match the correct pattern");
}
我得到这个输出:
cdrFiles length: 1
there is 1 or more files
有谁知道这怎么可能?
编辑:
这是过滤器的代码:
String[] cdrFiles = collectCdrFiles(directory, new FilenameFilter() {
public boolean accept(File dir, String name) {
System.out.println(name + "\t" + name.matches("call_history_[0-9]{8}_[0-9]{8}_[0-9]{3}_answer.*\.csv"));
return name.matches("call_history_[0-9]{8}_[0-9]{8}_[0-9]{3}_answer.*\.csv"));
}
});
第一个代码不打印文件名。
使用第二个代码(甚至检查它是否匹配 -> 是)
目录中的文件:
call_history_20111001_20111031_465_answer.csv
collectCdrFiles 函数如下所示:
protected String[] collectCdrFiles(String directory, FilenameFilter filter) throws IOException {
//open cdr directory
String[] cdrFiles;
File dir = new File(directory);
//get cdr files
if (dir.exists()) {
cdrFiles = dir.list(filter);
System.out.println("cdrFiles length: " + cdrFiles.length);
if (cdrFiles.length >= 1) {
System.out.println("there is 1 or more files");
}else{
throw new IOException("1No files in dir: " + directory + " that match the correct pattern");
}
} else {
throw new IOException("Directory: " + directory + " doesn't exist.");
}
return cdrFiles;
}
这段代码有同样的问题:
if (cdrFiles.length >= 1) {
System.out.println("there is 1 or more files");
}
if(cdrFiles.length == 0){
throw new IOException("1No files in dir: " + directory + " that match the correct pattern");
}
SSCCEE:
public static void main(String[] args) throws IOException {
String[] cdrFiles;
File dir = new File("testfolder");
//get cdr files
if (dir.exists()) {
cdrFiles = dir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
System.out.println(name + "\t" + name.matches("call_history_[0-9]{8}_[0-9]{8}_[0-9]{3}_answer.*\\.csv"));
return name.matches("call_history_[0-9]{8}_[0-9]{8}_[0-9]{3}_answer.*\\.csv");
}
});
System.out.println("cdrFiles length: " + cdrFiles.length);
if (cdrFiles.length >= 1) {
System.out.println("there is 1 or more files");
}
if(cdrFiles.length == 0){
throw new IOException("1No files in dir: " + dir.getName() + " that match the correct pattern");
}
} else {
throw new IOException("Directory: " + dir.getName() + " doesn't exist.");
}
}
}