0

how can I get all files in folder only by name without extension file? for example I have picture name "pic1" and I don't know extension it can be "gif","jpeg","png" I tried that but it's also looking for extension:

   File dir = new File("...");
    String[] files = dir.list(new NameFileFilter("pic1"));
    for (int i = 0; i < files.length; i++) {
        System.out.println(files[i]);
    }

thank,

reference
  • 51
  • 1
  • 5
  • Have you looked into similar threads http://stackoverflow.com/questions/924394/how-to-get-file-name-without-the-extension and http://stackoverflow.com/questions/17741170/how-to-find-file-without-extension – Santhosh Nov 24 '14 at 14:30
  • You can check this link out : http://stackoverflow.com/questions/1310877/how-to-open-file-without-extension – Jeshen Appanna Nov 24 '14 at 14:33

3 Answers3

1
String[] files = dir.list(new FilenameFilter() {
    @Override
    boolean accept(File dir, String name) {
        //return name.startsWith("pic1.");
        return name.matches("(?i)pic1\\.(gif|jpg|jpeg|png)");
    }
});

Java 8:

String[] files = dir.list((dir, name) -> name.startsWith("pic1."));
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

List the files without providing a filter, then loop on the list: if fileNameString.startsWith("pic1") then do your logic.

To do this more correctly, use FilenameUtils.removeExtension() from Apache Commons IO (on the file name).

abdelrahman-sinno
  • 1,157
  • 1
  • 12
  • 33
0

Since you're already using the Apache library, try:

FileFilter fileFilter = new WildcardFileFilter("pic1.*");
String[] files = dir.list(fileFilter);
martinez314
  • 12,162
  • 5
  • 36
  • 63