
import java.io.FileInputStream;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Calculatingword {

   public static void main(String args[]) throws Exception {
    String file = "/home/girish/Desktop/D.txt";
    
    FileInputStream inputStream = new FileInputStream(file);
    FileChannel fileChannel = inputStream.getChannel();
    System.out.println(fileChannel);
    int fileLength = (int) fileChannel.size();
    MappedByteBuffer mbb = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0,
        fileLength);
    
    Charset charset = Charset.forName("ISO-8859-1");
    CharsetDecoder cd = charset.newDecoder();
    
    CharBuffer charBuffer = cd.decode(mbb);
    System.out.println("========================" +
            "File from where words are counted=============");
    System.out.println(charBuffer);
     System.out.println("========================" +
             "===================================");
    
    Pattern pattern = Pattern.compile(".*$", Pattern.MULTILINE);
    Pattern patternword = Pattern.compile("[\\p{Punct}\\s}]");

    Matcher Lmatcher = pattern.matcher(charBuffer);
    Map map = new TreeMap();
    Integer one = new Integer(1);

    while (Lmatcher.find()) {
      CharSequence sequence = Lmatcher.group();
      String word[] = patternword.split(sequence);

      for (int i = 0, n = word.length; i < n; i++) {
        if (word[i].length() > 0) {
          Integer times = (Integer) map.get(word[i]);
          if (times == null) {
            times =one;
          } else {
            int value = times.intValue();
            times = new Integer(value + 1);
          }
          map.put(word[i], times);
        }
      }
    }
    System.out.println("No of times words repeted are :"+"\n"+map);
  }
}
