Lista plików w katalogu pasującym do wzorca w Javie [duplikat]

to pytanie ma już odpowiedzi tutaj : Jak znaleźć pliki pasujące do łańcucha znaków wieloznacznych w Javie? (16 odpowiedzi) Zamknięty 1 rok temu .

Szukam sposobu na uzyskanie listy plików pasujących do wzorca (Pref regex) w danym katalogu.

Znalazłem tutorial online, który używa pakietu commons-io apache o następującym kodzie:

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

Ale to po prostu zwraca kolekcję bazową(zgodnie z docs jest to kolekcja java.io.File). Czy istnieje sposób, aby to zrobić, który zwraca typ safe generic collection?

 89
Author: skaffman, 2010-01-20

6 answers

Zobacz Plik#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);
}
 138
Author: Kevin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-20 16:28:10

Od Javy 8 można używać lambda i uzyskać krótszy kod:

File dir = new File(xmlFilesDirectory);
File[] files = dir.listFiles((d, name) -> name.endsWith(".xml"));
 60
Author: mr T,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-12 13:58:19

Od Javy 7 Możesz java.pakiet nio {[3] } aby osiągnąć ten sam wynik:

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);
}
 26
Author: Tarek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-31 18:43:30

Poniższy kod utworzy listę plików na podstawie metody accept 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
        }}));
 14
Author: jjnguy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-20 16:30:41

A co z opakowaniem wokół istniejącego kodu:

public Collection<File> getMatchingFiles( String directory, String extension ) {
     return new ArrayList<File>()( 
         getAllFilesThatMatchFilenameExtension( directory, extension ) );
 }
Rzucę jednak Ostrzeżenie. Jeśli możesz żyć z tym ostrzeżeniem, to jesteś skończony.
 0
Author: OscarRyz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-20 16:37:46
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
    }
}
 0
Author: Manash Ranjan Dakua,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-19 10:06:11