twisted
twisted

Reputation: 21

Getting the list of files within a directory that has lots of files in java

Will using the list() method in the File class give issues if its a directory with thousands of files in it? Could this cause the array returned to use too much memory?

What alternative is there?

Upvotes: 1

Views: 394

Answers (4)

Shakeel Osmani
Shakeel Osmani

Reputation: 13

import java.io.*;
import java.util.*;

public class prog14{
    public static void main(String[] args){
        String path = "";
        System.out.print("Enter the folder path: ");
        Scanner scn = new Scanner(System.in);
        path = scn.nextLine();
        File[] files = new File(path).listFiles();
        for (File file : files) 
        {
            System.out.println(file.getName());
        }
    }
}

Upvotes: 0

jt78
jt78

Reputation: 926

I may be wrong about this, but surely there is no possible way to economise the amount of data returned. The returned array will always use the the amount of bytes needed to store the same number of strings as there are files in the directory. The only ways I can see to reduce memory usage are to use some complex string compression technique or just organise your files into folders and then use the list method on only the ones you need to. Hope that helps.

Upvotes: 0

pajton
pajton

Reputation: 16246

Unlikely. You should be just fine using File.list(). Thousands of file names is not much in terms of memory.

As for alternatives, there aren't any "better ways" to do it in Java and as I already said, you probably won't need them.

Upvotes: 1

Rom1
Rom1

Reputation: 3207

Unlikely (this would amount to allocating a few megabytes, top). Try it first, search for workarounds only if it is a real issue :)

Upvotes: 0

Related Questions