При запуске программы с параметрами "-u id productName price quantity" должна обновится информация о товаре в файле.
При запуске программы с параметрами "-d id" строка товара с заданным id должна быть удалена из файла.
package com.javarush.task.task18.task1828;
/*
Прайсы 2
*/
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
public class Solution {
//private static final String TMP_FILE = "/tmp/tmp_file.txt";
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
reader.close();
String operation = null;
if (args.length > 0) {
operation = args[0];
}
String id = null;
if (args.length > 1) {
id = args[1];
}
String productName = null;
if (args.length > 2) {
productName = args[2];
}
String price = null;
if (args.length > 3) {
price = args[3];
}
String quantity = null;
if (args.length > 4) {
quantity = args[4];
}
//operation = "-d";
//operation = "-u";
//id="19847";
//productName = "productName";
//price = "price";
//quantity = "quantity";
//String fileName = "/tmp/test.txt";
if (operation != null && ("-u".equals(operation) || "-d".equals(operation))) {
String line;
File readFile = new File(fileName);
//File writeFile = new File(TMP_FILE);
//StringBuilder tmp = new StringBuilder();
List<String> list = new LinkedList<>();
try (BufferedReader fileReader = new BufferedReader(new FileReader(readFile))) {
//try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(writeFile))) {
while ((line = fileReader.readLine()) != null) {
String currentId = line.substring(0, 8).trim();
boolean isWrite = true;
if (Objects.equals(id, currentId)) {
if ("-d".equals(operation)) {
isWrite = false;
}
if ("-u".equals(operation)) {
StringBuilder outputString = new StringBuilder();
outputString.append(addSpace(String.valueOf(id), 8));
outputString.append(addSpace(String.valueOf(productName), 30));
outputString.append(addSpace(String.valueOf(price), 8));
outputString.append(addSpace(String.valueOf(quantity), 4));
line = outputString.toString();
}
}
if (isWrite) {
list.add(line);
//tmp.append(line);
//tmp.append("\n");
// fileWriter.write(line + "\n");
}
}
}
try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(fileName))) {
int size = list.size();
int count = 0;
for (String s : list) {
count++;
fileWriter.write(s);
if(count < size) {
fileWriter.newLine();//write("\n");
}
}
//fileWriter.write();
//fileWriter.write(tmp.toString());
//writeFile.renameTo(readFile);
}
}
}
private static String addSpace(String inputStr, int lenght) {
if (inputStr.length() > lenght) {
return inputStr.substring(0, lenght);
}
if (inputStr.length() == lenght) {
return inputStr;
}
return addSpace(inputStr + " ", lenght);
}
}