对于在指定目录下实现遍历其所有子文件的实现

特地来强调一下这个方法

下面这个图片,是利用递归来遍历输出指定目录下的子文件路径名:

上述内容是遍历输出指定目录下的子文件路径名,要是想要实现循环遍历该目录下的所有子文件,并实现上一篇提到的统计单词的功能,可以这样做:

//Main.java
public static void main(String[] args) throws IOException {
        String s;

        File file=new File("D:\\Study\\Code\\JavaWeb\\IDEA\\tt1021");
        fileName(file);

    }

    public static void fileName(File file) throws IOException {
        File[] listfiles=file.listFiles();
        for(File ff:listfiles){
            if(ff.isDirectory()){
                fileName(ff);
            }
            else{
                System.out.println(ff);

                String s;
                int count=0;
                int num=1;
                BufferedReader br=new BufferedReader(new FileReader(ff));

                StringBuffer sb=new StringBuffer();
                while((s=br.readLine())!=null){
                    sb.append(s);
                }
                String m=sb.toString().toLowerCase();

                String[] mm=m.split("[^a-zA-z0-9]+");

                Map<String,Integer> map=new TreeMap<String,Integer>();

                for(int i=0;i<mm.length;i++){
                    if(map.containsKey(mm[i])){
                        count=map.get(mm[i]);
                        map.put(mm[i],count+1);
                    }else{
                        map.put(mm[i],1);
                    }
                }

                List<Map.Entry<String,Integer>> list=new ArrayList<Map.Entry<String,Integer>>(map.entrySet());

                for(Map.Entry<String,Integer> ma:list){
                    System.out.println(ma.getKey()+":"+ma.getValue());
                }
             }
        }
    }

即在原来仅仅遍历子文件路径的基础上,在那个子方法里面放置进行该文件的内容的输出;
大体上的思路不变,就是将原来在psvm里面的输出语句啥的放到了递归方法里面。

posted @ 2022-10-22 12:48  yesyes1  阅读(11)  评论(0编辑  收藏  举报