java如何查找目录下是否有特定文件

2024-12-23 11:12:16
推荐回答(1个)
回答1:

package com.cn.leng;

import java.io.File;
import java.io.FilenameFilter;

public class ListFile {

private String filepre;//文件前缀

private String filesux;//文件后缀

public void listFile(String dir, String prefix, String suffix){

File fileTarget = new File(dir);//取得目标目录

filepre = prefix;

filesux =suffix;

if(fileTarget.exists()){//判断目录是否存在

File[] fileLogs = fileTarget.listFiles(

new FilenameFilter(){

public boolean accept(File dir, String name) {

return ((name.startsWith(filepre))&&(name.endsWith(filesux)));//使用FilenameFilter类过滤取得满足指定条件的文件的文件数组

}

}

);

if(fileLogs.length > 0){

for(int i = 0; i
System.out.println(fileLogs[i].getName());

}

}else{

System.err.println("we cant find the file start with:"+ prefix);

System.exit(0);

}

}else{

System.err.print("we cant find the path:"+ fileTarget);

}

}

public static void main(String[] args) {

ListFile lf = new ListFile();

lf.listFile("C:\swserver\ipe113\logs","eai","log");

}

}