java - 按扩展名列出和计数文件

标签 java list recursion count java.util.scanner

到目前为止,我有这样的代码:

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

public class Test {
static Scanner input = new Scanner(System.in);

public static void fileListing(File[] files, int depth) {
    if(depth == 0)
        return;
    else {
        for(File file: files) {
            if(file.isDirectory())
                fileListing(file.listFiles(), depth-1);
            else {
                String ext;
                String fileName = file.getName();
                if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
                    ext = fileName.substring(fileName.lastIndexOf(".")+1);
                else
                    return;
                System.out.println(ext);
            }
        }
    }
}

public static void main(String [] args) {
    System.out.printf("Path: ");
    String path = input.nextLine();

    if(new File(path).isDirectory()) {
        System.out.printf("Depth: ");
        int depth = input.nextInt();
        File[] file = new File(path).listFiles();
        fileListing(file, depth);
    }
    else {
        System.out.printf("The path %s isn't valid.", path);
        System.exit(0);
    }
  }
}

我的输出列出了某个目录中的文件扩展名,例如。克。

txt
txt
doc

如何改进此代码以使用计数器显示文件扩展名?例如上面的例子,输出应该是这样的:

2 txt
1 doc

最佳答案

您可以使用 map :代码为:

    Map<String,Integer> countExt = new HashMap<String,Integer>();

   // Start from here inside your if statement
       ext = fileName.substring(fileName.lastIndexOf(".")+1);
    // If object already exists
    if(countExt.containsKey(ext)){
      Integer count = countExt.get(ext);
      count++;
     //Remove old object and add new
      countExt.remove(ext));
       countExt.put(ext,count);

    }
    // If extension is new 
    else
     countExt.put(ext,1);


    //For Display

    Set<String> keySet = countExt.keys();
    for(String key : keySet){
     System.out.println(key +" : "+countExt.get(key));

    }

关于java - 按扩展名列出和计数文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27111318/

相关文章:

java - 如何从服务器中的 FTP 位置读取大文件

java - 错误,我无法删除临时文件或将其替换为原始文件java

java - Thread Run() 后实例变量为空 - Java 扑克骰子程序

python - 在列表中查找包含最大数字的字符串

java - 递归迷宫算法

java - 在 Java 中递归生成字符串的幂集

java - 如何将用户输入添加到我的 Java 程序中以便在 if 语句中使用

java - 关于 JTextFields 和输入

c++ - 如何将元素添加到链表的末尾

javascript - jQuery ajax "too much recursion"