Counting the Number of Files in a Directory Using Java

Counting the number of files in a directory using Java

This might not be appropriate for your application, but you could always try a native call (using jni or jna), or exec a platform-specific command and read the output before falling back to list().length. On *nix, you could exec ls -1a | wc -l (note - that's dash-one-a for the first command, and dash-lowercase-L for the second). Not sure what would be right on windows - perhaps just a dir and look for the summary.

Before bothering with something like this I'd strongly recommend you create a directory with a very large number of files and just see if list().length really does take too long. As this blogger suggests, you may not want to sweat this.

I'd probably go with Varkhan's answer myself.

By java how to count file numbers in a directory without list()

If your only concern is to not create a List<File> you might use the Stream API.

long count = Files.list(Paths.get(path))
.filter(p -> p.toFile().isFile())
.count();
System.out.println("count = " + count);

edit The snippet is not meant to be fast. It was only provied for the requirement not to use list() or listFiles(). ;-)

Following a small comparison of different ways of counting the number of files in a directory containing two million files.

All commands are executed twice. First execution is with dropped file cache and the second execution followed right after the first one.

              | ls    | dir.list() | dir.listFiles() | Files.list(path)
--------------+-------+------------+-----------------+------------------
dropped cache | 9,120 | 5,518 | 5,879 | 59,175
filled cache | 946 | 1,992 | 2,401 | 51,179

times in milliseconds (the comma is the thousands separator)

Below the executed commands in detail.

ls

ls -f /tmp/huge-dir | wc -l

dir.list()

File hugeDir = new File("/tmp/huge-dir");
int numberFiles = hugeDir.list().length;

dir.listFile()

File hugeDir = new File("/tmp/huge-dir");
int numberFiles = hugeDir.listFiles().length;

Files.list(path)

Path path = Paths.get("/tmp/huge-dir");
long numberFiles = Files.list(path)
.filter(p -> p.toFile().isFile())
.count();

Based on those figures. Using dir.list().length seems to be not a bad solution.

Getting the number of files in a folder in java

From javadocs:

  • http://download.oracle.com/javase/6/docs/api/java/io/File.html

You can use:

new File("/path/to/folder").listFiles().length

get number of files in a directory and its subdirectories

Try this.

int count = 0;
getFile("/mnt/sdcard/folder/");

private void getFile(String dirPath) {
File f = new File(dirPath);
File[] files = f.listFiles();

if (files != null)
for (int i = 0; i < files.length; i++) {
count++;
File file = files[i];

if (file.isDirectory()) {
getFile(file.getAbsolutePath());
}
}
}

It may help you.

How to count the number of files in a directory, with the same file extension, in Java?

Pass your extension in this function.

amountOfFiles = files.map(Path::toFile).filter(e->e.getName().endsWith(".xml")).count();

How to count files in a directory

Your method is recursive which is a good idea, but you can't write something at the end of the recursion by placing it in the method itself (at least this way).
So, here is a possible correction. Make search a method that calculates how many files there is in (direct files, and file in its subdirs).

public static void main(String[] args) {    
System.out.println("# of files "+search("C:\\Program Files (x86)\\Adobe"));
}
public static int search(String folderpath){
File directory = new File(folderpath);
int numberOfFiles = 0;
for (File element : directory.listFiles()){
if (element.isDirectory()) { // count the files for this subdir
numberOfFiles += search(element.getAbsolutePath());
}
else { // one more file
numberOfFiles++;
System.out.println(element);
}
}
// return the number of files for this dir and its sub dirs
return numberOfFiles;
}

How to get number of files in a directory and subdirectory from a path in java?

Exception because :

readLine() method reads a entire line from the input but removes the
newLine characters from it.so it's unable to split around \n

Here is the code That does exactly what you want,.

I have a folderPath.txt which has a list of Directory like this.

D:\305

D:\Deployment

D:\HeapDumps

D:\Program Files

D:\Programming

This code gives you what you want + you can Modify it according to your need

public class Main {

public static void main(String args[]) throws IOException {

List<String> foldersPath = new ArrayList<String>();
File folderPathFile = new File("C:\\Users\\ankur\\Desktop\\folderPath.txt");

/**
* Read the folderPath.txt and get all the path and store it into
* foldersPath List
*/
BufferedReader reader = new BufferedReader(new FileReader(folderPathFile));
String line = reader.readLine();
while(line != null){
foldersPath.add(line);
line = reader.readLine();
}
reader.close();

/**
* Map the path(i.e Folder) to the total no of
* files present in that path (i.e Folder)
*/
Map<String, Integer> noOfFilesInFolder = new HashMap<String, Integer>();
for (String pathOfFolder:foldersPath){
File[] files2 = new File(pathOfFolder).listFiles();//get the arrays of files
int totalfilesCount = files2.length;//get total no of files present
noOfFilesInFolder.put(pathOfFolder,totalfilesCount);
}

System.out.println(noOfFilesInFolder);
}

}

Output:

{D:\Program Files=1, D:\HeapDumps=16, D:\Deployment=48, D:\305=4, D:\Programming=13}

Edit : This counts the total number of files present inside the subdirectory too.

/**This counts the
* total number of files present inside the subdirectory too.
*/
Map<String, Integer> noOfFilesInFolder = new HashMap<String, Integer>();
for (String pathOfFolder:foldersPath){
int filesCount = 0;
File[] files2 = new File(pathOfFolder).listFiles();//get the arrays of files
for (File f2 : files2){
if (f2.isDirectory()){
filesCount += new File(f2.toString()).listFiles().length;

}
else{
filesCount++;
}
}
System.out.println(filesCount);
noOfFilesInFolder.put(pathOfFolder, filesCount);
}

System.out.println(noOfFilesInFolder);
}

How to get a specific number of files from a directory?

Use Files and Path from the java.nio API instead of File.

You can also use them with Stream in Java 8 :

Path folder = Paths.get("...");
List<Path> collect = Files.walk(folder)
.filter(p -> Files.isRegularFile(p) && p.getFileName().toString().contains("key1"))
.limit(50)
.collect(Collectors.toList());

In Java 7, you could stop the file walking by using a SimpleFileVisitor implementation that takes care to terminate as 50 files matched the predicate:

List<Path> filteredFiles = new ArrayList<>();

SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (Files.isRegularFile(file) && file.getFileName()
.toString()
.contains("key1")) {
filteredFiles.add(file);
}

if (filteredFiles.size() == 50) {
return FileVisitResult.TERMINATE;
}
return super.visitFile(file, attrs);
}
};

and how use it :

final Path folder = Paths.get("...");

// no limitation in the walking depth
Files.walkFileTree(folder, visitor);

// limit the walking depth to 1 level
Files.walkFileTree(folder, new HashSet<>(), 1, visitor);


Related Topics



Leave a reply



Submit