现在的位置: 首页 > 综合 > 正文

文件夹下有子文件夹又有.txt,子文件夹又有子文件夹又有.txt和子文件夹,把txt文件上面的单词全打出来并统计相同单词出现次数

2018年05月09日 ⁄ 综合 ⁄ 共 2301字 ⁄ 字号 评论关闭

/**
 * 文件夹下的文件读取.
 * 该文件夹下面又又文件夹
 * 而再每个文件夹可能又一个
 * 或者多个.txt文件;
 * 当然了,你也可以自定义要查找的文件类型
 * 但是必须要.***的类型额
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

public class MyDir {
 //单词存再map中;
 private Map<String, Integer> words = new HashMap<String, Integer>();
 //查找出文件里面的单词,其中单词之间用" "分开;
 private Map<String, Integer> searchWord(String fileSource) {
  try {
   //创建文件读取;
   FileReader input = new FileReader(fileSource);
   //缓冲
   BufferedReader br = new BufferedReader(input);
   //行读
   String wordLine = "";
   //一行一行的读取,当他的行数还没有是null时候还读
   while ((wordLine = br.readLine()) != null) {
    //令牌读出一行的单词,用空格分开单词
    StringTokenizer word = new StringTokenizer(wordLine, " ");

    while (word.hasMoreTokens()) {
     //这里好象一定要这样用临时string,因为我用了几次直接word.nextToken();都提示说nullpointer异常
     String temp = word.nextToken();
     //如果map中的键已经有了,就把值取出来++;之后存上;
     if (words.containsKey(temp)) {
      int tempValue = words.get(temp).intValue();
      tempValue++;
      words.put(temp, tempValue);
     } else {
      //没有键的话直接存,这个1不是每个版本都能用这样的,好象是6.0版本的jdk会自动转化,
      //如果是早版本应该是
      //wrods.put(temp, new Integer(1));
      //这样才正确
      words.put(temp, 1);
     }
    }
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return words;

 }
 //该方法是为了打开文件夹下的.txt文件及文件夹;
 public Map<String, Integer> searchFile(String fileSource) {
  //打开文件路径
  File files = new File(fileSource);
  //文件是一个数组文件
  File[] sources = files.listFiles();
  //迭代出所有的文件(当然里面有文件夹,还有各种文件了;
  //这里只考虑了该文件下面仅有文件夹和.txt文件,没有其他的文件
  for (File f : sources) {
   //获取文件的名字;(当然包括文件夹和文件为.txt的记事本了;
   String tempName = f.getName();
   //如果是记事本.txt结尾的.就调用searchWord函数把里面的词读出来;
   if (tempName.endsWith(".txt")) {
    words = searchWord(fileSource + "/" + tempName); 
   } else {
    //否则就递归的调用该函数读取文件,
    //不过前面一定记得加上源文件名及"/"哦.不然就找不到路径了
    searchFile(fileSource + "/" + tempName);
   }
  }
  return words;
 }
 //为了方便,我就再这里测试了
 @SuppressWarnings("unchecked")
 public static void main(String[] args) {
  MyDir md = new MyDir();
  //文件夹为你要查找的文件夹D:/texttemp,以及要查找的类型了;
  Map<String, Integer> p = md.searchFile("D:/tomcat");
  Set s = p.entrySet();
  Iterator it = s.iterator();
  while(it.hasNext()) {
   System.out.print(it.next() + "  ");
  }
  System.out.println();
 }
}

抱歉!评论已关闭.