在与 Java 中的模式匹配的目录中列出文件

我正在寻找一种方法来获得一个在给定目录中匹配模式(pref regex)的文件列表。

我在网上找到了一个教程,它使用了 apache 的 commons-io 包,代码如下:

Collection getAllFilesThatMatchFilenameExtension(String directoryName, String extension)
{
File directory = new File(directoryName);
return FileUtils.listFiles(directory, new WildcardFileFilter(extension), null);
}

但是它只返回一个基本集合(根据 那些文件,它是 java.io.File的集合)。是否有办法返回类型安全的泛型集合?

134904 次浏览

See File#listFiles(FilenameFilter).

File dir = new File(".");
File [] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".xml");
}
});


for (File xmlfile : files) {
System.out.println(xmlfile);
}

The following code will create a list of files based on the accept method of the FileNameFilter.

List<File> list = Arrays.asList(dir.listFiles(new FilenameFilter(){
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".exe"); // or something else
}}));

What about a wrapper around your existing code:

public Collection<File> getMatchingFiles( String directory, String extension ) {
return new ArrayList<File>()(
getAllFilesThatMatchFilenameExtension( directory, extension ) );
}

I will throw a warning though. If you can live with that warning, then you're done.

Since java 7 you can the java.nio package to achieve the same result:

Path dir = ...;
List<File> files = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{java,class,jar}")) {
for (Path entry: stream) {
files.add(entry.toFile());
}
return files;
} catch (IOException x) {
throw new RuntimeException(String.format("error reading folder %s: %s",
dir,
x.getMessage()),
x);
}

Since Java 8 you can use lambdas and achieve shorter code:

File dir = new File(xmlFilesDirectory);
File[] files = dir.listFiles((d, name) -> name.endsWith(".xml"));
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;


public class CharCountFromAllFilesInFolder {


public static void main(String[] args)throws IOException {


try{


//C:\Users\MD\Desktop\Test1


System.out.println("Enter Your FilePath:");


Scanner sc = new Scanner(System.in);


Map<Character,Integer> hm = new TreeMap<Character, Integer>();


String s1 = sc.nextLine();


File file = new File(s1);


File[] filearr = file.listFiles();


for (File file2 : filearr) {
System.out.println(file2.getName());
FileReader fr = new FileReader(file2);
BufferedReader br = new BufferedReader(fr);
String s2 = br.readLine();
for (int i = 0; i < s2.length(); i++) {
if(!hm.containsKey(s2.charAt(i))){
hm.put(s2.charAt(i), 1);
}//if
else{
hm.put(s2.charAt(i), hm.get(s2.charAt(i))+1);
}//else


}//for2


System.out.println("The Char Count: "+hm);
}//for1


}//try
catch(Exception e){
System.out.println("Please Give Correct File Path:");
}//catch
}
}