-2

I have the following code. I cant find the source for the problem.

public class ConsoleApp1 {
    public static void main(String[] args) {
        allFiles("C:\\");
    }

    private static void allFiles(String root) {

        File ro = new File("e:\\");
        File[] flist = ro.listFiles();

        for (File i: flist) {
            if (i.isFile()) {
                System.out.println(i.getAbsolutePath());
            } else {
                allFiles(i.getAbsolutePath());
            }
        }
    }
}

I am in the future going to add this to swing application, A call from button will get the list and populate them into a JTree any advice on that would also help.

sidgate
  • 11,396
  • 8
  • 53
  • 100
Ak47
  • 45
  • 4
  • where did you use the **String root**. you are always get the list of files from **"e:\\"**. because of this its going inifinity call – subash Aug 11 '16 at 05:10

1 Answers1

4

You are recursively calling File constructor on E:\. You will eventually get stackoverflow error due to infinite loop. Change the constructor argument to use root variable.

private static void allFiles(String root) {
    File ro = new File(root);
    File[] flist = ro.listFiles();

    for(File i : flist){
        if(i.isFile()) {
            System.out.println(i.getAbsolutePath());
        }
        else {
            allFiles(i.getAbsolutePath());
        }
    }
}
sidgate
  • 11,396
  • 8
  • 53
  • 100
  • I have tried with the root variable now its throws a null pointer exception. – Ak47 Aug 11 '16 at 07:43
  • @Ak47 update ur question with complete stack trace. also look at http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it – sidgate Aug 11 '16 at 09:20
  • The problem arose because of '\' in the path whenever I use the getAbsolutePath() function. Thanks for the help. – Ak47 Aug 12 '16 at 11:36
  • @Ak47 plz accept the answer if the issue is resolved – sidgate Sep 12 '16 at 20:41