简体   繁体   English

获取目录及其子目录中的文件数

[英]get number of files in a directory and its subdirectories

using this code 使用此代码

new File("/mnt/sdcard/folder").listFiles().length

returns a sum of folders and files in a particular directory without caring about subdirectories . 返回特定目录中的文件夹和文件的总和,而不关心子目录 I want to get number of all files in a directory and its subdirectories. 我想获取目录及其子目录中所有文件的数量。

PS : hardly matters if it returns a sum of all the files and folders. PS:如果它返回所有文件和文件夹的总和几乎不重要。

any help appreciated, thanks 任何帮助表示感谢,谢谢

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. 它可能会帮助你。

You can use recursion. 你可以使用递归。

public static int getFilesCount(File file) {
  File[] files = file.listFiles();
  int count = 0;
  for (File f : files)
    if (f.isDirectory())
      count += getFilesCount(f);
    else
      count++;

  return count;
}

Using Java 8 NIO: 使用Java 8 NIO:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Test {

  public long fileCount(Path dir) { 
    return Files.walk(dir)
                .parallel()
                .filter(p -> !p.toFile().isDirectory())
                .count();
  }

  public void main(String... args) {
    Path dir = Paths.get(args[0]);
    long count = fileCount(dir);

    System.out.println(args[0] + " has " + count + " files");
  }

}
public Integer countFiles(File folder, Integer count) {
    File[] files = folder.listFiles();
    for (File file: files) {
        if (file.isFile()) {
            count++;
        } else {
            countFiles(file, count);
        }
    }

    return count;
}

Usage: 用法:

Integer count = countFiles(new File("your/path"), Integer.valuOf(0));

you will have to do a recursive search over your files. 你将不得不对你的文件进行递归搜索。 Use `File#isDrirectory()´ to check if a file is a directory and traverse the file tree down. 使用`File#isDrirectory()'检查文件是否是目录并遍历文件树。

You have to go though all the folder recursively and find out the files 你必须递归遍历所有文件夹并找出文件

int mCount;

getTotalFiles(File dir) {
    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            getTotalFiles(file);
        } else {
            mCount++;
        }
    }
}

Something I've used before, you can easily edit it to get what you want: 我之前使用的东西,您可以轻松编辑它以获得您想要的东西:

public class Filewalker {

    public void walk( String path ) {

        File root = new File( path );
        File[] list = root.listFiles();

        for ( File f : list ) {
            if ( f.isDirectory() ) {
                walk( f.getAbsolutePath() );
                System.out.println( "Dir:" + f.getAbsoluteFile() );
            }
            else {
                System.out.println( "File:" + f.getAbsoluteFile() );
            }
        }
    }

    public static void main(String[] args) {
        Filewalker fw = new Filewalker();
        fw.walk("c:\\" );
    }
}

Here's a short one all encapsulated within a single method just returning the number of files and directories within a specific directory: 这里只是一个简短的封装在一个方法中,只返回特定目录中的文件和目录的数量:

public static int countFiles(File directory) {
    int count = 0;
    for (File file : directory.listFiles()) {
        if (file.isDirectory()) {
            count += countFiles(file); 
        }
        count++;
    }
    return count;
}

Cheers! 干杯!

Just for the record, you may also use iteration instead of recursion: 只是为了记录,您也可以使用迭代而不是递归:

public static int countFiles(final File dir) {
    final ArrayDeque<File> dirs = new ArrayDeque<>();
    dirs.add(dir);
    int cnt = 0;
    while (!dirs.isEmpty()) {
        final File[] files = dirs.poll().listFiles();
        for (final File f: files)
            if (f.isDirectory())
                dirs.add(f);
            else
                ++cnt;
    }
    return cnt;
}

In this implementation I'm using ArrayDeque but you can use any Queue or any List for the job. 在这个实现中我使用的是ArrayDeque,但你可以使用任何Queue或任何List来完成这项工作。

public int numberOfFiles(File srcDir) {
    int count = 0;
    File[] listFiles = srcDir.listFiles();
    for(int i = 0; i < listFiles.length; i++){
        if (listFiles[i].isDirectory()) {
            count += numberOfFiles(listFiles[i]);
        } else if (listFiles[i].isFile()) {
            count++;
        }
    }
    return count;
}

http://www.java2s.com/Code/Java/File-Input-Output/Countfilesinadirectoryincludingfilesinallsubdirectories.htm http://www.java2s.com/Code/Java/File-Input-Output/Countfilesinadirectoryincludingfilesinallsubdirectories.htm

 public static int countFilesInDirectory(File directory) { int count = 0; for (File file : directory.listFiles()) { if (file.isFile()) { count++; } if (file.isDirectory()) { count += countFilesInDirectory(file); } } return count; } 

refer this site 参考这个网站

it gives perfect answer 它给出了完美的答案

import java.io.File;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {


     Scanner sc=new Scanner(System.in);  

     System.out.println("Enter the Path for Directory/Folder Name");  
     String Directory=sc.nextLine(); 
     System.out.println("Your Directory/folder is :"+Directory);

     File f = new File(Directory);

     int countFiles = 0;
     int countDirectory=0;
     for (File file : f.listFiles()) {
             if (file.isFile()) {
                     countFiles++;
             }
             if (file.isDirectory()) {
                     countDirectory++;
             }

     }
     System.out.println("Number of files in Directory : " + countFiles+"\nNumber of Sub-directories "+countDirectory);

    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 快速列出目录及其所有子目录中的文件 - Fast listing files in a directory and all of its subdirectories 以递归方式获取Java中的目录及其子目录中的所有文件 - Non-recursive way to get all files in a directory and its subdirectories in Java 如何在hadoop hdfs中列出目录及其子目录中的所有文件 - How to list all files in a directory and its subdirectories in hadoop hdfs 在 Java 中递归压缩包含任意数量的文件和子目录的目录? - Recursively ZIP a directory containing any number of files and subdirectories in Java? 搜索目录及其子目录中的所有 po 文件,并创建一个 Hashmap,其中包含文件路径作为值,其目录作为键 - Search for all po files in a directory and its subdirectories and create a Hashmap containing the filepaths as value and its directory as key 如何使用Java的目录流仅在目录中而不是其他子目录中获取文件/子目录 - How to use Java's directory stream to get files/subdirectories only within directory not other subdirectories 如何使用正则表达式获取目录中不包含子目录的所有文件? - How to get all files in a directory with exclusion of subdirectories using regular expression? Java,仅列出目录中的子目录,而不是文件 - Java, List only subdirectories from a directory, not files 如何使用Java获取目录及其子目录中多个文件的相同xml元素值? - How to get the same xml element value of multiple files in a directories and its subdirectories using java? 重命名目录和一些包含文件/子目录 - Renaming directory and some of the containing files/subdirectories
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM