Reputation: 782
Using Java, what is the most resource efficient way to pull a 'list' of files names from a folder location. At the moment I am using the code below:-
File[] files = new File(folderLocation).listFiles();
Before iterating through the file array and dumping the filenames only, into a Hash to be used by my application. So, bearing in mind that I only need the file name's is there a more memory efficient way to do this.
Edit:
Upvotes: 0
Views: 518
Reputation: 410
Do you need to differentiate between files and directories. If not, you can use the list() function in File to return an array of strings naming the files and directories in the directory denoted by this abstract pathname. Then, you can easily construct a HashSet with that list. For example,
String[] files = new File(folderLocation).list();
Set<String> mySet = new HashSet<String>(Arrays.asList(files));
There is also a list(FilenameFilter filter) function which accepts a file name filter and returns a list of String names. However, it doesn't allow you to filter based on file/directory.
Upvotes: 1
Reputation: 282
You can use (new File(folderLocation)).list()
which returned String[]. Each String is path+separator+filename. You can extract filename from this Strings.
Upvotes: 2
Reputation: 2614
you can check Path
it is mentioned in javadoc
Path getFileName()
Returns the name of the file or directory denoted by this path as a Path object
Upvotes: 0
Reputation: 121712
Using Java 7+ there is:
final Path dir = Paths.get(folderLocation);
final List<String> names = new ArrayList<>();
try (
final DirectoryStream<Path> dirstream
= Files.newDirectoryStream(dir);
) {
for (final Path entry: dirstream)
list.add(entry.getFileName());
}
Also, well, File.listFiles()
just doesn't work.
Upvotes: 0