Created
August 7, 2016 08:38
-
-
Save cyberterror/1f5ad480177a5e60b4a97043bfb619f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.InputStreamReader; | |
/** Задача проходит, но все равно есть непонятный косяк с переносами строк*/ | |
public class Solution { | |
public static void main(String[] args) throws Exception { | |
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); | |
String filename = reader.readLine(); | |
reader.close(); | |
/** Находим максимальный id из файла */ | |
int maxId = 0; | |
BufferedReader reader1 = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); | |
while (true) { | |
String line = reader1.readLine(); | |
if (line == null) break; | |
if (line.equals("")) continue; | |
String idString = line.substring(0,8); | |
if (idString.contains(" ")) { | |
int offset = idString.indexOf(' '); | |
idString = idString.substring(0,offset); | |
} | |
int id = Integer.parseInt(idString); | |
/** Если полученный индекс больше чем максимальный присваиваем его максимальному*/ | |
if (maxId < id) { | |
maxId = id; | |
} | |
} | |
reader1.close(); | |
/** Строка id для нового товара 8 символов */ | |
int id = maxId + 1; | |
String idString = String.valueOf(id); | |
idString = correctLength(idString, 8); | |
/** Строка имени для нового товара 30 символов */ | |
String nameString = ""; | |
for (int index = 1; index < args.length - 2; index++) { | |
nameString += args[index]; | |
nameString += " "; | |
} | |
nameString = correctLength(nameString, 30); | |
/** Строка цены для нового товара 8 символов*/ | |
float price = Float.parseFloat(args[args.length - 2]); | |
String priceString = String.valueOf(price); | |
priceString = correctLength(priceString, 8); | |
/** Строка количества для нового товара 4 символа*/ | |
int quantity = Integer.parseInt(args[args.length - 1]); | |
String quantityString = String.valueOf(quantity); | |
quantityString = correctLength(quantityString, 4); | |
/** Строка которая пойдет в файл*/ | |
String string = idString + nameString + priceString + quantityString; | |
byte[] bytes = string.getBytes(); | |
FileOutputStream fileOutputStream = new FileOutputStream(filename, true); | |
fileOutputStream.write(bytes); | |
fileOutputStream.write("\n".getBytes()); | |
fileOutputStream.close(); | |
} | |
private static String correctLength(String string, int length) | |
{ | |
String result = string; | |
if (result.length() < length) { | |
int spaces = length - result.length(); | |
for (int index = 0; index < spaces; index ++) { | |
result += " "; | |
} | |
} | |
else if (result.length() > length) { | |
result = result.substring(0,length); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment