2014-11-24 94 views
1

计数文件到目前为止,我有这样的代码:清单,并通过它们的扩展

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); 
    } 
    } 
} 

我的输出列表中的文件中的某个目录的扩展,E。 G。

txt 
txt 
doc 

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

2 txt 
1 doc 

回答

0

您可以使用地图吧:代码是:

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)); 

    } 
+0

现在看看我的代码,我增加了一个扩展微调。你能告诉我如何为我的代码添加一个计数器吗?或者如何将您的代码与我的代码合并? – JohnDoe 2014-11-24 19:27:39