Advertisement
jaVer404

level18.lesson10.home08_releaseCandidate_2

Jan 14th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.02 KB | None | 0 0
  1. package com.javarush.test.level18.lesson10.home08;
  2.  
  3. import java.io.*;
  4. import java.util.HashMap;
  5. import java.util.HashSet;
  6. import java.util.Map;
  7.  
  8. /* Нити и байты
  9. Читайте с консоли имена файлов, пока не будет введено слово "exit"
  10. Передайте имя файла в нить ReadThread
  11.  
  12. Нить ReadThread должна найти байт, который встречается в файле максимальное число раз,
  13. и добавить его в словарь resultMap,
  14. где параметр String - это имя файла, параметр Integer - это искомый байт.
  15.  
  16. Закрыть потоки. Не использовать try-with-resources
  17. */
  18. /*
  19. 1. В main, пока не ввели слово exit считываются имена файлов
  20. 2. Имя файла передается в нить ReadThread (как???)
  21. 3. Нить читает и считает файл и файл и байт в словарь.
  22. Проблема:
  23.  1. Конструктор ReadThread
  24. */
  25.  
  26. /*
  27. *Пока не ввели exit создаем (через конструктор) новую нить ReadThread
  28.  Передаем туда имя файла с консоли, она читает файл, считает и добавляет в словарь.
  29. *
  30. * ATTENTION
  31. 1. Если файл не найден, искать новый - читать новый файл
  32. 2. Если два байта с одинаковым количеством "попаданий". Кидать оба.
  33. * */
  34.  
  35. public class Solution {
  36.     public static Map<String, Integer> resultMap = new HashMap<String, Integer>();
  37.  
  38.     public static void main(String[] args) throws IOException {
  39.        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  40.         String consoleInput = "";
  41.         while (true) {
  42.             consoleInput=reader.readLine();
  43.             if (consoleInput.equals("exit")) {
  44.                 break;
  45.             }
  46.             else {
  47.                     new ReadThread(consoleInput).start();//it would be different threads
  48.             }
  49.         }
  50.         reader.close();
  51.  
  52.         /*---------------------------------------------*/
  53. /*        for (Map.Entry<String, Integer> entry : resultMap.entrySet()) {
  54.             String key = entry.getKey().toString();;
  55.             Integer value = entry.getValue();
  56.             System.out.println("key, " + key + " value " + value );
  57.         }*/
  58.         /*---------------------------------------------*/
  59.     }
  60.  
  61.     public static class ReadThread extends Thread {
  62.         public ReadThread(String fileName) {
  63.             //implement constructor body
  64.             super(fileName);
  65.         }
  66.  
  67.  
  68.         // implement file reading here - реализуйте чтение из файла тут
  69.         public void run() {
  70.             try {
  71.                 String fileName = this.getName();
  72.                 byte[]bytes = fileToArray(this.getName());//тут выдает ошибку
  73.                 HashSet<Byte>setBytes = countBytes(bytes);
  74.                 resultMap.put(fileName,returnByte(bytes, setBytes));
  75.             }
  76.             catch (Exception e) {
  77.             }
  78.         }
  79.     }
  80. /*
  81. /*-------------------------------------------------------*/
  82.     public static byte[] fileToArray (String fileName) throws IOException
  83.     {
  84.  
  85.             File file = new File(fileName);
  86.             byte[] bFile = new byte[(int) file.length()];
  87.             FileInputStream  fileInputStream = new FileInputStream(file);
  88.             fileInputStream.read(bFile);
  89.             fileInputStream.close();
  90.             return bFile;
  91.     }
  92.  
  93.     public static HashSet<Byte>countBytes (byte[]bytesArray) {
  94.         HashSet<Byte> allBytes = new HashSet<Byte>();
  95.         for (int i = 0; i < bytesArray.length;i++) {
  96.             allBytes.add(bytesArray[i]);
  97.         }
  98.         return allBytes;
  99.     }
  100.  
  101.     public static int countSpecByte (byte myByte, byte[]someArray)/*Не нужно тут выкидывать исключения*/
  102.     {
  103.         int counter = 0;
  104.         for (byte b : someArray) {
  105.             if (myByte == b) {
  106.                 counter++;
  107.             }
  108.         }
  109.         return  counter;
  110.     }
  111.  
  112.     public static int returnByte (byte[]someBytes, HashSet<Byte>someUniqeBytes) {
  113.         HashMap<Byte, Integer> bytesAndCounts = new HashMap<Byte, Integer>();
  114.         for (byte specByte : someUniqeBytes) {
  115.             bytesAndCounts.put(specByte, countSpecByte(specByte,someBytes));
  116.         }
  117.         Map.Entry<Byte, Integer> maxEntry = null;
  118.         for (Map.Entry<Byte, Integer> entry : bytesAndCounts.entrySet())
  119.         {
  120.             if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)//может тут и два одинаковых влепить
  121.             {
  122.                 maxEntry = entry;
  123.             }
  124.         }
  125.         return maxEntry.getKey();
  126.     }
  127.  /*---------------------------------------------------------------------------*/
  128. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement