How to Find List of Files Located in a Folder in Java?
Share
Condition for Finding List of Files Located in a Folder in Java
Description: To find a list of files located in a folder in Java, the File class from the java.io package can be used. A File object is created representing the folder, and the listFiles() method is called on this object to retrieve an array of File objects representing the files and directories within the folder. To filter out only the files (excluding directories), a check can be performed using File.isFile() on each element of the array. Alternatively, Files.walk() from the java.nio.file package can be used for more advanced directory traversal, providing a stream of files that can be filtered or processed as needed. Both approaches allow for retrieving files in the specified folder, with the option to filter by file extensions or perform other criteria-based searches.
Sample Source Code
# ListOfFiles.java package JavaSamples;
import java.io.File;
public class ListOfFiles extends javax.swing.JFrame {
jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jButton2 = new javax.swing.JButton();
if (files != null) { for (File file : files) { if (file.isFile()) { jTextArea1.append("File: " + file.getName() + "\n"); } } } else { jTextArea1.append("Folder is empty or does not exist.\n"); }
}//GEN-LAST:event_jButton2ActionPerformed
public static void main(String args[]) { java.awt.EventQueue.invokeLater(() -> { new ListOfFiles().setVisible(true); }); }
// Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables
Screenshots
STEP 1: The user selects a folder from local files.
STEP 2: To click the choose folder button, it navigates the local device to choose a folder.
STEP 3: The folder path will be displayed in the text field.
STEP 4: Once the user clicks the 'List Of Files' button, it automatically lists out all the files in the selected folder.