Advertisement
jaVer404

level18.lesson10.home06(not compile)

Dec 16th, 2015
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.53 KB | None | 0 0
  1. package com.javarush.test.level18.lesson10.home06;
  2.  
  3. /* Встречаемость символов
  4. Программа запускается с одним параметром - именем файла, который содержит английский текст.
  5. Посчитать частоту встречания каждого символа.
  6. Отсортировать результат по возрастанию кода ASCII (почитать в инете). Пример: ','=44, 's'=115, 't'=116
  7. Вывести на консоль отсортированный результат:
  8. [символ1]  частота1
  9. [символ2]  частота2
  10. Закрыть потоки. Не использовать try-with-resources
  11.  
  12. Пример вывода:
  13. , 19
  14. - 7
  15. f 361
  16. */
  17.  
  18. import java.io.*;
  19. import java.util.HashMap;
  20. import java.util.TreeSet;
  21. public class Solution {
  22.  
  23.  
  24.     public static void main(String[] args) throws IOException
  25.     {
  26.         TreeSet<Integer> fromFile = treeSetFromFile(args[0]);
  27.         byte[]allBytes = bytesFromFile(args[0]);
  28.         HashMap<Character, Integer> keyAndValue = new HashMap<Character, Integer>();
  29.         int counter = 0;
  30.         for (int i : fromFile) {
  31.             counter=countChar((char)i, allBytes);
  32.             keyAndValue.put((char)i,counter);
  33.         }
  34.         for (HashMap.Entry<Character, Integer> entry: keyAndValue.entrySet()) {
  35.             System.out.println(entry.getKey()+" "+entry.getValue());
  36.         }
  37.     }
  38.  
  39.  
  40.     /**
  41.      * Из файла в TreeSet
  42.      * */
  43.     public static TreeSet<Integer> treeSetFromFile (String s) throws IOException
  44.     {
  45.         FileInputStream fileInputStream = new FileInputStream(s);
  46.         TreeSet<Integer> asciiSet = new TreeSet<Integer>();
  47.         while (fileInputStream.available() > 0)
  48.         {
  49.             asciiSet.add(fileInputStream.read());
  50.         }
  51.         fileInputStream.close();
  52.         return asciiSet;
  53.     }
  54.  
  55.     public static byte[] bytesFromFile (String s) throws IOException{
  56.         FileInputStream fileInputStream=null;
  57.         File file = new File(s);
  58.         byte[] bFile = new byte[(int) file.length()];
  59.             fileInputStream = new FileInputStream(file);
  60.             fileInputStream.read(bFile);
  61.             fileInputStream.close();
  62.             return bFile;
  63. }
  64.     public static int countChar (char c, byte[]bytes) {
  65.         int counter = 0;
  66.         for (byte b : bytes) {
  67.             if ((char)b==c) {
  68.                 counter++;
  69.             }
  70.         }
  71.         return counter;
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement