Условие:
Прайсы 2
CrUD для таблицы внутри файла
Считать с консоли имя файла для операций CrUD
Программа запускается с одним из следующих наборов параметров:
-u id productName price quantity
-d id
Значения параметров:
где id — 8 символов
productName — название товара, 30 chars (60 bytes)
price — цена, 8 символов
quantity — количество, 4 символа
-u — обновляет данные товара с заданным id
-d — производит физическое удаление товара с заданным id (все данные, которые относятся к переданному id)
В файле данные хранятся в следующей последовательности (без разделяющих пробелов):
id productName price quantity
Данные дополнены пробелами до их длины
Пример:
19846 Шорты пляжные синие 159.00 12
198478 Шорты пляжные черные с рисунко173.00 17
19847983Куртка для сноубордистов, разм10173.991234
Требования:
1. Программа должна считать имя файла для операций CrUD с консоли.
2. При запуске программы без параметров список товаров должен остаться неизменным.
3. При запуске программы с параметрами "-u id productName price quantity" должна обновится информация о товаре в файле.
4. При запуске программы с параметрами "-d id" строка товара с заданным id должна быть удалена из файла.
5. Созданные для файлов потоки должны быть закрыты.
Результаты проверки:
Разработал следующее решение:
package com.javarush.task.task18.task1828;
/*
Прайсы 2
*/
import java.io.*;
import java.util.LinkedHashMap;
import java.util.Map;
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Map<Integer, Position> positions = new LinkedHashMap<>();
if (args.length < 2) {
return;
}
Integer id = Integer.parseInt(cast(args[1], 8).trim());
String operation = args[0];
String fileName = reader.readLine();
try {
FileInputStream fis = new FileInputStream(fileName);
BufferedReader fileReader = new BufferedReader(new InputStreamReader(fis));
while (fileReader.ready()) {
String entry = fileReader.readLine();
Position position = parseEntry(entry);
positions.put(position.id, position);
}
fis.close();
} catch (FileNotFoundException e) {
}
if (!positions.containsKey(id)) {
return;
}
if (operation.equals("-u")) {
if (args.length < 5) {
return;
}
String productName = args[2];
Double price = Double.parseDouble(cast(args[3], 8).trim());
Integer quantity = Integer.parseInt(cast(args[4], 4).trim());
Position position = positions.get(id);
position.setProductName(productName);
position.setQuantity(quantity);
position.setPrice(price);
} else if (operation.equals("-d")) {
positions.remove(id);
} else {
return;
}
FileOutputStream fout = new FileOutputStream(fileName);
PrintStream out = new PrintStream(fout);
for (Map.Entry<Integer, Position> position : positions.entrySet()) {
out.println(position.getValue());
}
fout.close();
}
public static String cast(String src, int length) {
if (src.length() > length) {
return src.substring(0, length);
}
return src;
}
public static Position parseEntry(String entry) {
int id = Integer.parseInt(entry.substring(0, 8).trim());
String productName = entry.substring(8, 38).trim();
double price = Double.parseDouble(entry.substring(38, 46).trim());
int quantity = Integer.parseInt(entry.substring(46, 50).trim());
return new Position(id, productName, price, quantity);
}
public static class Position {
private int id;
private String productName;
private double price;
private int quantity;
public Position(int id, String productName, double price, int quantity) {
this.id = id;
this.productName = productName;
this.price = price;
this.quantity = quantity;
}
public void setProductName(String productName) {
this.productName = productName;
}
public void setPrice(double price) {
this.price = price;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(trimAndPad(this.id, 8));
builder.append(trimAndPad(this.productName, 30));
builder.append(trimAndPad(this.price, 8));
builder.append(trimAndPad(this.quantity, 4));
return builder.toString();
}
private String trimAndPad(Object input, int size) {
String data = input.toString();
String result;
if (data.length() > size) {
result = data.substring(0, size);
} else {
StringBuilder builder = new StringBuilder(data);
while (builder.length() < size) {
builder.append(' ');
}
result = builder.toString();
}
return result;
}
}
}
Однако получаю "При запуске программы с параметрами "-u id productName price quantity" должна обновится информация о товаре в файле.". Рекомендация от куратора: "Требование задачи не выполнено.". В чём проблема?