Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.javarush.test.level18.lesson10.bonus02;
- /* Прайсы
- CrUD для таблицы внутри файла
- Считать с консоли имя файла для операций CrUD
- Программа запускается со следующим набором параметров:
- -c productName price quantity
- Значения параметров:
- где id - 8 символов
- productName - название товара, 30 chars (60 bytes)
- price - цена, 8 символов
- quantity - количество, 4 символа
- -c - добавляет товар с заданными параметрами в конец файла, генерирует id самостоятельно, инкрементируя максимальный id, найденный в файле
- В файле данные хранятся в следующей последовательности (без разделяющих пробелов):
- id productName price quantity
- Данные дополнены пробелами до их длины
- Пример:
- 19846 Шорты пляжные синие 159.00 12
- 198478 Шорты пляжные черные с рисунко173.00 17
- 19847983Куртка для сноубордистов, разм10173.991234
- */
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.InputStreamReader;
- public class Solution
- {
- public static void main(String[] args) throws Exception
- {
- if (args[0].equals("-c") && args.length >= 4)
- {
- BufferedReader userInput = null;
- BufferedReader fileReader = null;
- String fileName="";
- int max = 0;
- try
- {
- userInput = new BufferedReader(new InputStreamReader(System.in));
- fileName = userInput.readLine();
- userInput.close();
- fileReader = new BufferedReader(new FileReader(fileName));
- String fromFile;
- String cutFromFile;
- int temp = 0;
- while ((fromFile = fileReader.readLine()) != null)
- {
- cutFromFile = (fromFile.substring(0, 8)).trim();
- try
- {
- temp = Integer.parseInt(cutFromFile);
- if (temp > max)
- {
- max = temp;
- }
- }
- catch (Exception e)
- {
- }
- }
- }
- catch (Exception e)
- {
- }
- finally/*тут закрываем потоки, если они существуют*/
- {
- if (userInput != null)
- {
- userInput.close();
- }
- if (fileReader != null)
- {
- fileReader.close();
- }
- }
- max++;
- /*Now we have ID number*/
- String writeToFile =
- formNewPrice(max + "")
- + formNewProdName(args[1])
- + formNewPrice(args[2])
- + formNewQuan(args[3]);
- FileWriter fileWriter = null;
- try
- {
- fileWriter = new FileWriter(fileName,true);
- fileWriter.write(writeToFile);
- fileWriter.close();
- }
- catch (Exception e) {
- }
- finally
- {
- if (fileWriter!=null) {
- fileWriter.close();
- }
- }
- }
- }
- public static String formNewProdName(String input)
- {
- if (input.length() > 30)
- {
- return input.substring(0, 30);
- }
- return String.format("%-30s", input);
- }
- public static String formNewPrice(String input)
- {
- if (input.length() > 8)
- {
- return input.substring(0, 8);
- }
- return String.format("%-8s", input);
- }
- public static String formNewQuan(String input)
- {
- if (input.length() > 4)
- {
- return input.substring(0, 4);
- }
- return String.format("%-4s",input);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement