sabtharishi
sabtharishi

Reputation: 3311

Java 7 - File.listFiles() cost of this operation

I have a scenario where I have to loop through file contents for multiple purposes. My question here is, is it Ok to call file.listFiles() multiple times? Is this an expensive operation? Or should I store this this into a variable and use it in all the places?

The problem here is. I may have 3 or 4 levels. In each level, I have to validate or carry some logics. I have to start from the folder 1 and do logic 1 till folder 4. Then again I have to start from folder 1 to perform logic 2 and then for logic 3 and so on.

Folder 1
 - Folder 2
 - File1
      - Folder 3
      - File2
           - Folder 4
           - File3

Upvotes: 0

Views: 329

Answers (3)

Bot
Bot

Reputation: 11

Use,

    Path searchPath = Paths.get("c://log");
    try (DirectoryStream<Path> fileList = Files.newDirectoryStream(searchPath)) {
      for (Path path : fileList) {
        System.out.println(path.getFileName());
      }

Its less resource intensive and provides overloaded methods for pattern matching too.

Upvotes: 0

Austin
Austin

Reputation: 8585

Bottom Line Up Front (BLUF): Calling file.listFiles() multiple times will likely cause little/no impact on performance.

I wrote a test case to measure the amount of time it takes to list the contents of a local directory 10,000 times. I used a 2.9Ghz dual-core Windows 10 machine. There were 45 files of varying size in the directory. Here's the test case:

class Foo {

    public static void main(String[] args) {
        File f = Paths.get(System.getProperties().get("user.home")+"").toFile();
        long startTime = System.currentTimeMillis();
        for(int i = 0; i < 10000; i++){
            f.listFiles()[0].toString();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("Total Time = " + (endTime - startTime));
    }
}

It produced the following output on the first run:

Total Time = 1337

This means that it takes less than 1ms to list the files.

Upvotes: 0

Nikesh Joshi
Nikesh Joshi

Reputation: 825

As per my Java experience I dont think operation is costly, It take n time to get all the file, where n is number of file.You can write recursive program to read the all directory of the folder.Recursive code will be easy to write but may little bit slower in performance.

 There is no guarantee that the name strings in the resulting array will  
 appear in any specific order; they are not, in particular, guaranteed to   
  appear in alphabetical order.  

  Note that the Files class defines the newDirectoryStream method to open a 
  directory and iterate over the names of the files in the directory. This 
  may use less resources when working with very large directories.

See here

See here Also

Upvotes: 1

Related Questions