To get a list of files in a directory in Java, you can use the File
class from the java.io
package. This class represents a file or directory in the file system, and provides methods for working with files and directories.
Here's an example of how to use the File
class to get a list of files in a directory:
import java.io.File; public class Main { public static void main(String[] args) { File directory = new File("/path/to/directory"); File[] files = directory.listFiles(); for (File file : files) { System.out.println(file.getName()); // prints the name of each file in the directory } } }Source:al.wwwutturi.com
In this example, a File
object is created for the directory. The listFiles()
method of the File
object is called to get an array of File
objects for the files in the directory. The array is then iterated over using a for-each loop, and the name of each file is printed to the console.
Please note that the listFiles()
method returns null
if the directory does not exist or if an error occurs. You should check for null
before iterating over the array.
You can use the various methods of the File
class to manipulate the files and directories, such as isDirectory()
to check if a file is a directory, or delete()
to delete a file.