Advertisement
jaVer404

level18.lesson10.bonus02 (done and tested(20))

Feb 15th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.43 KB | None | 0 0
  1. package com.javarush.test.level18.lesson10.bonus02;
  2.  
  3. /* Прайсы
  4. CrUD для таблицы внутри файла
  5. Считать с консоли имя файла для операций CrUD
  6. Программа запускается со следующим набором параметров:
  7. -c productName price quantity
  8.  
  9. Значения параметров:
  10. где id - 8 символов
  11. productName - название товара, 30 chars (60 bytes)
  12. price - цена, 8 символов
  13. quantity - количество, 4 символа
  14. -c  - добавляет товар с заданными параметрами в конец файла, генерирует id самостоятельно, инкрементируя максимальный id, найденный в файле
  15.  
  16. В файле данные хранятся в следующей последовательности (без разделяющих пробелов):
  17. id productName price quantity
  18. Данные дополнены пробелами до их длины
  19.  
  20. Пример:
  21. 19846   Шорты пляжные синие           159.00  12
  22. 198478  Шорты пляжные черные с рисунко173.00  17
  23. 19847983Куртка для сноубордистов, разм10173.991234
  24. */
  25.  
  26. import java.io.BufferedReader;
  27. import java.io.FileReader;
  28. import java.io.FileWriter;
  29. import java.io.InputStreamReader;
  30.  
  31. public class Solution
  32. {
  33.     public static void main(String[] args) throws Exception
  34.     {
  35.         if (args[0].equals("-c") && args.length >= 4)
  36.         {
  37.             BufferedReader userInput = null;
  38.             BufferedReader fileReader = null;
  39.             String fileName="";
  40.             int max = 0;
  41.             try
  42.             {
  43.                 userInput = new BufferedReader(new InputStreamReader(System.in));
  44.                 fileName = userInput.readLine();
  45.                 userInput.close();
  46.                 fileReader = new BufferedReader(new FileReader(fileName));
  47.                 String fromFile;
  48.                 String cutFromFile;
  49.                 int temp = 0;
  50.                 while ((fromFile = fileReader.readLine()) != null)
  51.                 {
  52.                     cutFromFile = (fromFile.substring(0, 8)).trim();
  53.                     try
  54.                     {
  55.                         temp = Integer.parseInt(cutFromFile);
  56.                         if (temp > max)
  57.                         {
  58.                             max = temp;
  59.                         }
  60.                     }
  61.                     catch (Exception e)
  62.                     {
  63.                     }
  64.                 }
  65.             }
  66.             catch (Exception e)
  67.             {
  68.             }
  69.             finally/*тут закрываем потоки, если они существуют*/
  70.             {
  71.                 if (userInput != null)
  72.                 {
  73.                     userInput.close();
  74.                 }
  75.                 if (fileReader != null)
  76.                 {
  77.                     fileReader.close();
  78.                 }
  79.             }
  80.             max++;
  81.             /*Now we have ID number*/
  82.             String writeToFile =
  83.                               formNewPrice(max + "")
  84.                             + formNewProdName(args[1])
  85.                             + formNewPrice(args[2])
  86.                             + formNewQuan(args[3]);
  87.             FileWriter fileWriter = null;
  88.             try
  89.             {
  90.                 fileWriter = new FileWriter(fileName,true);
  91.                 fileWriter.write(writeToFile);
  92.                 fileWriter.close();
  93.             }
  94.             catch (Exception e) {
  95.  
  96.             }
  97.             finally
  98.             {
  99.                 if (fileWriter!=null) {
  100.                     fileWriter.close();
  101.                 }
  102.             }
  103.  
  104.         }
  105.  
  106.     }
  107.  
  108.     public static String formNewProdName(String input)
  109.     {
  110.         if (input.length() > 30)
  111.         {
  112.             return input.substring(0, 30);
  113.         }
  114.  
  115.         return String.format("%-30s", input);
  116.     }
  117.  
  118.     public static String formNewPrice(String input)
  119.     {
  120.         if (input.length() > 8)
  121.         {
  122.             return input.substring(0, 8);
  123.         }
  124.         return String.format("%-8s", input);
  125.     }
  126.  
  127.     public static String formNewQuan(String input)
  128.     {
  129.         if (input.length() > 4)
  130.         {
  131.             return input.substring(0, 4);
  132.         }
  133.         return String.format("%-4s",input);
  134.     }
  135. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement