0

I do not want to use traditional approach of creating a new file object for each of the path name(file/dir) i want to check the existence for. e.g in below code:

    public class FileChecker {

    public static void main(String args[]) {

      File f1 = new File("home/usr/data1");
      File f2 = new File("home/usr/data2")

      if(f1.exists()){
          System.out.println("File existed");
      }else{
          System.out.println("File not found!");
      }

      if(f2.exists()){
          System.out.println("File existed");
      }else{
          System.out.println("File not found!");
      }
  }

}

I have to create a new object for each candidate file whose existence i want to check,I think this approach will monotonously fill heap space if my list of files(that need to be checked for existence is large). Is there any other approach to achieve the same without creating so many File objects?

dsingh
  • 270
  • 1
  • 5
  • 17
  • 2
    No. You could list all the files in a directory, but you'll still end up with loads of `File` objects. Why are you worried about the stack space? – Dawood ibn Kareem Apr 03 '14 at 00:26
  • Well, that check should be a method not inline code (anytime you start writing the same thing over and over again--it's a dead giveaway it should be a method). There's no way I know of to check whether a file exists other than by creating a `File` object. And if you make it a method so that it only checks one file at a time, it won't fill the heap (which is where all of those `File` objects go--not the stack) due to garbage collection. – Jared Apr 03 '14 at 00:26
  • 1
    Object creation is cheap, and the GC is designed on the assumption that many objects are short-lived. If you really think this is a problem then _measure_ it with a profiler before you spend time trying to improve it - you'll almost certainly find that it's not worth the effort. – Ian Roberts Apr 03 '14 at 00:27
  • @IanRoberts OP asked about the stack, not the heap. So the garbage collection is not the issue. It's just the number of variables in the method. Using an array or some kind of Collection would solve this, of course. So would doing it in a loop. – Dawood ibn Kareem Apr 03 '14 at 00:29
  • Unless the code is automatically generated, I don't see how you could possibly write enough code to create a problem for the stack in this case. – Jared Apr 03 '14 at 03:22

1 Answers1

1

If you know the folder where you want to check the files, here is an approach to find the existence of the file, without creating so many File objects -

File folder = new File("<directory_name>");
ArrayList<String> fileNames = new ArrayList<String>(Arrays.asList(folder.list()));
fileNames.contains("my file");
hellboy
  • 2,222
  • 1
  • 14
  • 19