Getting the filenames of all files in a folder [duplicate] Getting the filenames of all files in a folder [duplicate] java java

Getting the filenames of all files in a folder [duplicate]


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?


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());    }}


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.