Advertisement
jaVer404

level18.lesson10.home08_releaseCandidate_3

Jan 14th, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.07 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(fileName);//тут выдает ошибку
  73.                 HashSet<Byte>setBytes = countBytes(bytes);
  74.                 synchronized (resultMap) {
  75.                     resultMap.put(fileName,returnByte(bytes, setBytes));
  76.                 }
  77.  
  78.             }
  79.             catch (IOException e) {
  80.             }
  81.         }
  82.     }
  83.     /*
  84.     /*-------------------------------------------------------*/
  85.     public static byte[] fileToArray (String fileName) throws IOException
  86.     {
  87.  
  88.         File file = new File(fileName);
  89.         byte[] bFile = new byte[(int) file.length()];
  90.         FileInputStream  fileInputStream = new FileInputStream(file);
  91.         fileInputStream.read(bFile);
  92.         fileInputStream.close();
  93.         return bFile;
  94.     }
  95.  
  96.     public static HashSet<Byte>countBytes (byte[]bytesArray) {
  97.         HashSet<Byte> allBytes = new HashSet<Byte>();
  98.         for (int i = 0; i < bytesArray.length;i++) {
  99.             allBytes.add(bytesArray[i]);
  100.         }
  101.         return allBytes;
  102.     }
  103.  
  104.     public static int countSpecByte (byte myByte, byte[]someArray)/*Не нужно тут выкидывать исключения*/
  105.     {
  106.         int counter = 0;
  107.         for (byte b : someArray) {
  108.             if (myByte == b) {
  109.                 counter++;
  110.             }
  111.         }
  112.         return  counter;
  113.     }
  114.  
  115.     public static int returnByte (byte[]someBytes, HashSet<Byte>someUniqeBytes) {
  116.         HashMap<Byte, Integer> bytesAndCounts = new HashMap<Byte, Integer>();
  117.         for (byte specByte : someUniqeBytes) {
  118.             bytesAndCounts.put(specByte, countSpecByte(specByte,someBytes));
  119.         }
  120.         Map.Entry<Byte, Integer> maxEntry = null;
  121.         for (Map.Entry<Byte, Integer> entry : bytesAndCounts.entrySet())
  122.         {
  123.             if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)//может тут и два одинаковых влепить
  124.             {
  125.                 maxEntry = entry;
  126.             }
  127.         }
  128.         return maxEntry.getKey();
  129.     }
  130.  /*---------------------------------------------------------------------------*/
  131. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement