List Folder Contents in Java

Often Java Developers stumble across a simple situation and end up googling the web to find the best code which can help to solve their needs. One such situation is - How to write a simple java program that lists the contents of a folder. There are quite a lot of solutions available for this, but I would like to post a working solution which can sometime prove really handy in solving the question. Next time you want to list the contents of a directory and are after a java code, check out in thinktibits..

Code:
-----
import java.io.File;
public class save{
    public void showDirectoryList() {
        File dir = new File("C:/temp");
        File[] list = dir.listFiles();
        for (int i=0; i
            if (list[i].isFile()) {
                System.out.println("File "+list[i].getName());
                } else if (list[i].isDirectory()) {
                System.out.println("Directory "+list[i].getName());
            }
        }
    }
    public static void main (String args[]) {
        save s = new save();
        s.showDirectoryList();
    }
}

No comments:

Post a Comment