id инкрементируется, пробелы добавляются, строки дописываются. Валидатор весь энтузиазм себя проявить портит(, что ему надо
// args = new String[]{"-c", "Куртка для сноубордистов, разммер", "10173.99", "1234"};
if (args.length > 0 && args[0].equals("-c")) {
int idLen = 8;
int productLen = 30;
int priceLen = 8;
int quantityLen = 4;
String productId;
String productName = args[1];
String price = args[2];
String quantity = args[3];
if (productName.length() > productLen)
productName = productName.substring(0, productLen);
if (price.length() > priceLen)
price = price.substring(0, priceLen);
if (quantity.length() > quantityLen)
quantity = quantity.substring(0, quantityLen);
Scanner scanner = new Scanner(System.in);
String fileName = scanner.nextLine();
scanner.close();
Scanner fileScanner = new Scanner(new FileInputStream(fileName));
int maxId = -1;
while (fileScanner.hasNext()) {
String line = fileScanner.nextLine();
int id = Integer.valueOf(line.substring(0, idLen).replace(" ", ""));
if (id > maxId)
maxId = id;
}
fileScanner.close();
productId = String.valueOf(maxId + 1);
for (int i = productId.length(); i < idLen; i++)
productId += " ";
for (int i = productName.length(); i < productLen; i++)
productName += " ";
for (int i = price.length(); i < priceLen; i++)
price += " ";
for (int i = quantity.length(); i < quantityLen; i++)
quantity += " ";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.write(productId + productName + price + quantity);
writer.newLine();
writer.flush();
writer.close();
}package com.javarush.task.task18.task1827;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
/*
Прайсы
*/
public class Solution {
public static void main(String[] args) throws Exception {
// args = new String[]{"-c", "Куртка для сноубордистов, разм", "10173.99", "1234"};
if (args.length > 0 && args[0].equals("-c")) {
int idLen = 8;
int productLen = 30;
int priceLen = 8;
int quantityLen = 4;
String id = "-1";
String productName = args[1];
String price = args[2];
String quantity = args[3];
Scanner scanner = new Scanner(System.in);
String fileName = scanner.nextLine();
scanner.close();
Scanner fileScanner = new Scanner(new FileInputStream(fileName));
String lastLine = "";
while (fileScanner.hasNext()) {
lastLine = fileScanner.nextLine();
}
fileScanner.close();
if (!lastLine.isEmpty())
id = lastLine.substring(0, idLen).replace(" ", "");
id = String.valueOf(Integer.parseInt(id) + 1);
for (int i = id.length(); i < idLen; i++)
id += " ";
for (int i = productName.length(); i < productLen; i++)
productName += " ";
for (int i = price.length(); i < priceLen; i++)
price += " ";
for (int i = quantity.length(); i < quantityLen; i++)
quantity += " ";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.write(id + productName + price + quantity);
writer.newLine();
writer.flush();
writer.close();
}
}
}