Прошу помочь
package com.javarush.task.task18.task1827;
/*
Прайсы
1. Программа должна считать имя файла для операций CrUD с консоли.
2. В классе Solution не должны быть использованы статические переменные.
3. При запуске программы без параметров список товаров должен остаться неизменным.
4. При запуске программы с параметрами "-c productName price quantity" в конец файла должна добавится новая строка с товаром.
5. Товар должен иметь следующий id, после максимального, найденного в файле.
6. Форматирование новой строки товара должно четко совпадать с указанным в задании.
7. Созданные для файлов потоки должны быть закрыты.
*/
import java.text.*;
import java.util.*;
import java.io.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) throws Exception {
/* //testing
// id(8) productName(30) price(8) quantity(4)
String inputString = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String command ="";
String sourceFileName = "";
String productName = "";
String price = "";
String quantity = "";
String args1 = reader.readLine();
//
sourceFileName= reader.readLine();
File file=new File(sourceFileName);
if (file.exists()){
System.out.printf("File=%s exists!\n",file);
}
BufferedWriter writer = new BufferedWriter(new FileWriter(sourceFileName,true));
Pattern pattern = Pattern.compile("\\s*(-(c|u|d)) ([a-zA-Zа-яА-Я_ -]+) ([0-9]+(\\.)?([0-9]+)?) ([0-9]+)\\s*");
//Pattern pattern = Pattern.compile("\\b[a-zA-Z]"+part+"\\b", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(args1);
if (matcher.matches()) {
command = matcher.group(1);
productName = matcher.group(3);
price = matcher.group(4);
quantity = matcher.group(7);
System.out.printf("command =%s\nsource=%s\nproduct=%s\nprice=%s\nquant=%s\n",command,sourceFileName,productName,price,quantity);
} else {
System.out.println("wrong input string !");
}
args= new String[]{"", "", ""} ;
// testing end*/
// //real prog
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String sourceFileName= reader.readLine();
BufferedWriter writer = new BufferedWriter(new FileWriter(sourceFileName,true));
if (args.length > 0) {
String command = args[0];
String productName = args[1];
String price = args[2];
String quantity = args[3];
//
List <String> fileContentStrings =new ArrayList<>() ;
BufferedReader reader2 = new BufferedReader(new FileReader(sourceFileName));
String str="";
while (true) {
try {
if ((str = reader2.readLine()) == null) {
break;
} else {
fileContentStrings.add(str);
// System.out.printf("added string=%s\n", str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
reader2.close();
//
switch (command) {
case "-c": {
int fileStringsCount=0;
List <Integer> fileStringsIDs =new ArrayList<>();
for (String fileString: fileContentStrings) {
Pattern pattern2 = Pattern.compile("\\s?([0-9 ]{8})([a-zA-Zа-яА-Я_ -]{30})([0-9., ]{8})([0-9 ]{4})\\s?");
//Pattern pattern = Pattern.compile("\\b[a-zA-Z]"+part+"\\b", Pattern.CASE_INSENSITIVE);
Matcher matcher2 = pattern2.matcher(fileString);
if (matcher2.matches()) {
//System.out.println("ID="+matcher2.group(1).trim());
int stringID=Integer.parseInt(matcher2.group(1).trim());
fileStringsIDs.add(stringID);
fileStringsCount++;
/* command = matcher.group(2);
productName = matcher.group(3);
price = matcher.group(4);
quantity = matcher.group(5);*/
//System.out.printf("command =%s;\nsource=%s;\nproduct=%s\n;price=%s;\nquant=%s;\n",command,sourceFileName,productName,price,quantity);
} else {
//System.out.println("no matching strings found!!");
}
}
//System.out.printf("command =%s\nsource=%s\nproduct=%s\nprice=%s\nquant=%s\n",command,sourceFileName,productName,price,quantity);
Collections.sort(fileStringsIDs);
// id(8) productName(30) price(8) quantity(4)
String idToAdd="";
if (fileStringsIDs.size()>0 ) {
idToAdd = (fileStringsIDs.get(fileStringsIDs.size() - 1) + 1) + "";
} else{
idToAdd="1";
}
if(idToAdd.length()>8){
idToAdd=idToAdd.substring(0,7);
} else if (idToAdd.length()<8){
idToAdd=addChars(idToAdd,' ',8-idToAdd.length(),2) ;
}
if(productName.length()>30){
productName=productName.substring(0,29);
} else if (productName.length()<30){
productName=addChars(productName,' ',30-productName.length(),2) ;
}
if(price.length()>8){
price=price.substring(0,7);
} else if (price.length()<8){
price=addChars(price,' ',8-price.length(),2) ;
}
if(quantity.length()>4){
quantity=quantity.substring(0,3);
} else if (quantity.length()<4){
quantity=addChars(quantity,' ',4-quantity.length(),2) ;
}
//System.out.printf("New string:id=%s\nproduct=%s\nprice=%s\nquant=%s\n",idToAdd,productName,price,quantity);
writer.write(idToAdd+productName+price+quantity);
writer.newLine();
writer.flush();
break;
}
case "-u": {
break;
}
case "-d": {
break;
}
case "-i": {
break;
}
}
}
reader.close();
writer.close();
}
public static String addChars(String str, char c, int qty, int side) {
final StringBuilder sb = new StringBuilder();
if (qty>0) {
final char[] arr = new char[qty];
Arrays.fill(arr, c);
switch (side) {
case 1:
sb.append(arr).append(str);
break;
case 2:
sb.append(str).append(arr);
break;
case 3:
sb.append(arr).append(str).append(arr);
break;
default:
throw new IllegalArgumentException("Непонятно с какой стороны добавлять");
}
}
return sb.toString();
}
}