package com.javarush.test.level18.lesson10.home06; /* Встречаемость символов Программа запускается с одним параметром - именем файла, который содержит английский текст. Посчитать частоту встречания каждого символа. Отсортировать результат по возрастанию кода ASCII (почитать в инете). Пример: ','=44, 's'=115, 't'=116 Вывести на консоль отсортированный результат: [символ1] частота1 [символ2] частота2 Закрыть потоки. Не использовать try-with-resources Пример вывода: , 19 - 7 f 361 */ import java.io.*; import java.util.HashMap; import java.util.TreeSet; public class Solution { public static void main(String[] args) throws IOException { TreeSet fromFile = treeSetFromFile(args[0]); byte[]allBytes = bytesFromFile(args[0]); HashMap keyAndValue = new HashMap(); int counter = 0; for (int i : fromFile) { counter=countChar((char)i, allBytes); keyAndValue.put((char)i,counter); } for (HashMap.Entry entry: keyAndValue.entrySet()) { System.out.println(entry.getKey()+" "+entry.getValue()); } } /** * Из файла в TreeSet * */ public static TreeSet treeSetFromFile (String s) throws IOException { FileInputStream fileInputStream = new FileInputStream(s); TreeSet asciiSet = new TreeSet(); while (fileInputStream.available() > 0) { asciiSet.add(fileInputStream.read()); } fileInputStream.close(); return asciiSet; } public static byte[] bytesFromFile (String s) throws IOException{ FileInputStream fileInputStream=null; File file = new File(s); byte[] bFile = new byte[(int) file.length()]; fileInputStream = new FileInputStream(file); fileInputStream.read(bFile); fileInputStream.close(); return bFile; } public static int countChar (char c, byte[]bytes) { int counter = 0; for (byte b : bytes) { if ((char)b==c) { counter++; } } return counter; } }