Advertisement
AlexMatveev

Untitled

Feb 17th, 2012
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. package ru.nsu.ccfit.matveev;
  2.  
  3. import java.util.*;
  4. import java.util.Map.Entry;
  5. import java.lang.StringBuilder;
  6. import java.io.*;
  7.  
  8. public class lab1 {
  9.  
  10.     private static void getInfo(String file) {
  11.         Reader reader = null;
  12.         HashMap<String, Integer> hm = new HashMap<String, Integer>();
  13.         try {
  14.             long count = 0;
  15.             reader = new InputStreamReader(new FileInputStream(file));
  16.             while (reader.ready()) {
  17.                 char ch;
  18.                 StringBuilder sb = new StringBuilder();
  19.                 while (Character.isLetterOrDigit(ch = (char) reader.read()))
  20.                     sb.append(ch);
  21.                 if (0 == sb.length())
  22.                     continue;
  23.                 count++;
  24.                 String str = sb.toString();
  25.                 if (hm.containsKey(str)) {
  26.                     int value = (Integer) hm.get(sb.toString()) + 1;
  27.                     hm.put(str, value);
  28.                 } else
  29.                     hm.put(str, 1);
  30.             }
  31.             List<Entry<String, Integer>> s = new ArrayList<Entry<String, Integer>>(
  32.                     hm.entrySet());
  33.             Collections.sort(s, new Comparator<Entry<String, Integer>>() {
  34.                 public int compare(Entry<String, Integer> o1,
  35.                         Entry<String, Integer> o2) {
  36.                     return -o1.getValue().compareTo(o2.getValue());
  37.                 }
  38.             });
  39.             for(Entry<String, Integer> e: s){
  40.                 double percent = ((Integer) e.getValue()).doubleValue();
  41.                 System.out.printf("%s;%d;%3.2f%%\n", e.getKey(),
  42.                         e.getValue(), percent / count * 100);
  43.             }
  44.         } catch (IOException e) {
  45.             System.err.println("Error while reading file: "
  46.                     + e.getLocalizedMessage());
  47.         } finally {
  48.             if (null != reader) {
  49.                 try {
  50.                     reader.close();
  51.                 } catch (final IOException e) {
  52.                     e.printStackTrace(System.err);
  53.                 }
  54.             }
  55.         }
  56.     }
  57.  
  58.     public static void main(String[] args) {
  59.             String file = args[0];
  60.             getInfo(file);
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement