3 Replies Latest reply: Aug 8, 2010 5:27 PM by EJP RSS

    how to stop execution if File array is empty

      Hi experts,

      I have developed this code to collect files from the folder. This code is working fine when folder exist either the data exists in the folder or not. but if the folder does not exist it raises an error...
      File f1 = new File(path);
                          File[] file = null;
                          file = f1.listFiles();
                          if(file.length != 0){
                          fileName = new String[file.length];
                          for(int x =0;x<file.length; x++){
                              arr = file[x].toString().split("/");
                              fileName[x] = arr[arr.length-2] + "/" + arr[arr.length-1];
      i know i can use try catch to handle this one, but i want to use if() condition as i used some of them like...
      if(file[0] != null)
      On the behalf of
       if(file.length != 0)
      but they dont work for me, and whenever i am using if condition to block the piece of code the expression in if() condition generates error.
      Please guide me what should i use to block the execution of code.

        • 1. Re: how to stop execution if File array is empty
          You'll get better help if you provide an SSCCE that shows the whole picture (but no unnecessary fluff), rather than just isolated snippets.

          Also, "it raises an error" is meaningless. You are aware that there's more than one kind of exception, right? And you are aware that different kinds of exceptions indicate different kinds of problems, requiring different kinds of solutions, right? And you are aware that to fix an error, one has to know where it occurred, right? So perhaps in the future you could consider pasting in the exact, complete error message, and indicating clearly exactly which line caused it.

          Based on the limited information you've provided, I can only offer this general advice:

          File has an exists() method to test if a given file or directory exists.

          As for testing for length being zero before looping, you don't need to do that.
          int[] arr = new int[0]
          for (int x : arr) {
            // do stuff
          // OR
          for (int i = 0; i < arr.length; i++) {
            // do stuff
          If the length is zero, the loop body will never be entered.
          • 2. Re: how to stop execution if File array is empty
            Thanks for your help.
            Now it is working fine...
            • 3. Re: how to stop execution if File array is empty
              File.listFiles() can return null under certain conditions: see the Javadoc. You're not testing for that. You need to do that first, then loop over the array if it isn't null. You dont need to check for files.length being null explicitly, the loop does that, and you don't need to check for individual elements of the array being null: they aren't.