Better Understanding Java Concepts : File , Exception Handling -


i want build data structure store files file-system. have class directorynode:

class directorynode{     private string name;     private string path;     file file;      //this list stores sub-directories of given directory.      private list<directorynode> subdirectories = new arraylist<directorynode>();      //this list stores simple files of given directory      private list<string> filenames = new arraylist<string>();      //the default constructor.     directorynode(file directoryname){         this.name = directoryname.getname();         this.path = directoryname.getpath();         this.file = directoryname;         //a function build directory.         builddirectory();     }      file[] filesfromthisdirectory;      private void builddirectory(){         //get files directory         filesfromthisdirectory = file.listfiles();         try{             for(int = 0 ; < filesfromthisdirectory.length ; i++){                 if(filesfromthisdirectory[i].isfile()){                     this.filenames.add(filesfromthisdirectory[i].getname());                 } else if(filesfromthisdirectory[i].isdirectory()){                     directorynode dir = new directorynode(filesfromthisdirectory[i]);                     this.subdirectories.add(dir);                 }             }         }catch(exception e){             system.out.println(e.getmessage());         }     } } 

my program works fine weird behavior when don't use try- catch block in builddirectory() function. build function recursilvely builds structure list of files written in code.

when do:

directorynode d1 = new directorynode(new file("/")); 

when try-catch there , program works fine if remove try catch block : error after executing time: error :

 exception in thread "main" java.lang.nullpointerexception   @ directorynode.builddirectory(myclass.java:47)   @ directorynode.<init>(myclass.java:22)   @ directorynode.builddirectory(myclass.java:55)   @ directorynode.<init>(myclass.java:22)   @ directorynode.builddirectory(myclass.java:55)   @ directorynode.<init>(myclass.java:22)   @ myclass.main(myclass.java:75)  

but when run :

  directorynode d1 = new directorynode(new file("/home/neeraj")); 

with or without try - catch block , program runs fine without error. why ? why different results in these these scenarios?

the problem line:

    filesfromthisdirectory = file.listfiles(); 

this return null if file object not directory... or if don't have necessary privileges.

you must therefore check filesfromthisdirectory not null before entering loop.

but favour, drop file , use java.nio.file instead.


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -