ADVERTISEMENT
ADVERTISEMENT

Java program to get list of files, directories from a directory

Get list of files, directories from a directory - This program will print the name of files and directories which are available in a given directory.

To get the list of files we will use File.listFiles(), this method will return the name of all files and directories, and then we will check that item is a file or directory by using File.isFile() and File.isDirectory().

Get list of files, directories from a directory using Java program

import java.io.File;

class GetFilesFromDirectory {
  public static void main(String[] args) {
    File dirName = new File("D:/eclipse");
    File[] listFiles = dirName.listFiles();

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

Output:

    File: .eclipseproduct
    File: artifacts.xml
    Directory: configuration
    Directory: dropins
    File: eclipse.exe
    File: eclipse.ini
    File: eclipsec.exe
    File: epl-v10.html
    Directory: features
    File: notice.html
    Directory: p2
    Directory: plugins
    Directory: readme

Core Java Example Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.