454

I need to create a list with all names of the files in a folder.

For example, if I have:

000.jpg
012.jpg
013.jpg

I want to store them in a ArrayList with [000,012,013] as values.

What's the best way to do it in Java ?

PS: I'm on Mac OS X

Community
  • 1
  • 1
user680406
  • 5,637
  • 6
  • 24
  • 19

3 Answers3

826

You could do it like that:

File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
  if (listOfFiles[i].isFile()) {
    System.out.println("File " + listOfFiles[i].getName());
  } else if (listOfFiles[i].isDirectory()) {
    System.out.println("Directory " + listOfFiles[i].getName());
  }
}

Do you want to only get JPEG files or all files?

Andrei Suvorkov
  • 5,559
  • 5
  • 22
  • 48
RoflcoptrException
  • 51,941
  • 35
  • 152
  • 200
  • 3
    Yup there isn't but dealing with extensions is dependent on the extensions present cos files maybe present without extensions too. – Abhishek Apr 17 '11 at 15:45
  • 8
    btw if you want the current folder you can use `File folder = new File (".");` ... than the same. example `new File("./"+your_file);` – SüniÚr Oct 28 '14 at 08:25
  • 2
    @RoflcoptrException One doubt. Does this listofFiles[i] points to the first file in the folder (last created), or the last file (first created) ? – Justin George Jan 14 '15 at 09:07
  • 1
    in my folder are only *.xml files, is there any option to check that only those should be considered as files? – Jürgen K. Nov 02 '15 at 11:09
  • 2
    Just a suggestion, you could also use an enhanced for loop, like this: `for (File file : listOfFiles)`. Then you simply reference `file` in each iteration instead of `listOfFiles[i]`. – Stefan Carlson Jan 19 '16 at 15:27
  • 5
    How can get specify extension to get .jpg files? – Abc Aug 22 '16 at 02:17
  • 12
    If you want filter out only .JPG files and sort the result in oldest file first, you can use it like this: ```File dir = new File("/your/path"); FileFilter fileFilter = new WildcardFileFilter("*.JPG", IOCase.INSENSITIVE); // For taking both .JPG and .jpg files (useful in *nix env) File[] fileList = dir.listFiles(fileFilter); if (fileList.length > 0) { /** The oldest file comes first **/ Arrays.sort(fileList, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR); } //filesList now contains all the JPG/jpg files in sorted order``` – Dilip Muthukurussimana May 27 '18 at 13:23
  • @JustinGeorge From the JavaDocs it says that "There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order." – Kcits970 Mar 02 '20 at 08:47
158

Create a File object, passing the directory path to the constructor. Use the listFiles() to retrieve an array of File objects for each file in the directory, and then call the getName() method to get the filename.

List<String> results = new ArrayList<String>();


File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null. 

for (File file : files) {
    if (file.isFile()) {
        results.add(file.getName());
    }
}
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Sean Kleinjung
  • 3,115
  • 2
  • 21
  • 15
  • You should actually call `listFiles()` ;) – Progman Apr 17 '11 at 15:48
  • @Progman Could be helpful. :) – Sean Kleinjung Apr 17 '11 at 15:50
  • in my folder are only *.xml files, is there any option to check that only those should be considered as files? – Jürgen K. Nov 02 '15 at 11:10
  • 19
    You can put a filter on listFiles so as to only return files with a certain extension `File[] files = new File("/path/to/the/directory").listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".xml"); } }); ` – IanB Feb 18 '16 at 18:27
  • What if I want to both *.xml & *.txt files ? @IanB – sumitkanoje Jul 13 '16 at 06:26
  • @sumitkanoje you would change the filter to be return name.endsWith(".xml") || name.endsWith(".jpg") – IanB Nov 16 '16 at 09:18
  • 4
    File[] files = new File(fullPath).listFiles(); List names = Arrays.asList(files).parallelStream().map(file -> file.getName()).collect(Collectors.toList()); – Luke_P Jun 14 '17 at 14:04
  • 4
    You can filter files using *lambda* expression (Java 8+): `File[] files = new File("path/to/dir").listFiles((dir, name) -> name.endsWith(".xml"));` – Aleksandar Jun 25 '18 at 08:32
  • I was hoping that using filter does some sort of intelligent buffering but taking a look at java8 implementation of list(FilenameFilter filter) I am a little bit disappointed that it just do something like File root=File("/path/to/the/directory"); foreach(String filename : root.list()){accept(root,filename)} and then convert the result from List to String[]. – andrej Apr 11 '19 at 07:58
72

Here's how to look in the documentation.

First, you're dealing with IO, so look in the java.io package.

There are two classes that look interesting: FileFilter and FileNameFilter. When I clicked on the first, it showed me that there was a a listFiles() method in the File class. And the documentation for that method says:

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

Scrolling up in the File JavaDoc, I see the constructors. And that's really all I need to be able to create a File instance and call listFiles() on it. Scrolling still further, I can see some information about how files are named in different operating systems.

Muhd
  • 24,305
  • 22
  • 61
  • 78
Anon
  • 2,328
  • 12
  • 7