26 September 2016

Write a program in Java to show all files and directory name of a given location




Solution: 
If you want to run this Java program, you have to do the following:
  • Step1: Your computer must have JDK installed to run and compile any Java program.
  • Step2: Create a file name DirfileList.java with the source code given bellow and save the file on any location on your computer.
  • Step3: Compile and  Run the java program to get the output.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class DirfileList {

    public static void main(String[] args) {
        // TODO code application logic here

        try {
            // Set directory path name 
            File path = new File("F:/test");

            // Get list of files
            File[] listOfFiles = path.listFiles();

            // Declare file name list
            List<String> file_names = new ArrayList<String>();

            // Declare directory name list
            List<String> dir_names = new ArrayList<String>();

            // Loop throw the files and directory name and store the names in List
            for (int i = 0; i < listOfFiles.length; i++) {

                if (listOfFiles[i].isFile()) {
                    file_names.add(listOfFiles[i].getName());
                } else if (listOfFiles[i].isDirectory()) {
                    dir_names.add(listOfFiles[i].getName());
                }
            }

            // Print file names
            for (String fName : file_names) {
                System.out.println("File:" + fName);
            }

            // Print directory names
            for (String dName : dir_names) {
                System.out.println("Directory:" + dName);

            }
        } catch (Exception e) {
            System.out.println("!! Error:" + e.toString());
        }

    }

}

Java: A Beginner's Guide, Sixth Edition

Featured Post

How to Write PHP code and HTML code within a same file

A PHP file can have both PHP code and HTML code together. Any HTML code written outside of PHP <?php //php code here… ?> Code is ig...

Popular Posts