Строка добавляется, айди следующий после максимального устанавливается, форматирование то же самое.
Знаю что можно записать через String.format, но я его еще не изучил, после этого уровня займусь, потому обрезаю строки через костыли.
package com.javarush.task.task18.task1827;
import java.io.*;
/*
Прайсы
*/
public class Solution {
public static void main(String[] args) throws Exception {
try {
BufferedReader readerName = new BufferedReader(new InputStreamReader(System.in));
File file = new File(readerName.readLine());
FileOutputStream fileOutputStream = new FileOutputStream(file, true);
BufferedReader readerLine = new BufferedReader(new FileReader(file));
switch (args[0]) {
case "-c": {
String line;
int id, maxID = 0;
while ((line= readerLine.readLine()) != null) {
line = line.substring(0, 8).trim();
id = Integer.parseInt(line);
if (maxID < id)
maxID = id;
}
readerLine.close();
StringBuilder strId = new StringBuilder(String.valueOf(maxID + 1)); // Если айди короче 8, удлинняяем его
while (strId.length() < 8)
strId.append(" ");
StringBuilder strName = new StringBuilder(args[1]); // то же самое с Наименованием товара, если короче то удлинняяем, если длиннее, то обрезаем
String name;
if (strName.length() > 30)
name = strName.substring(0, 30);
else {
while (strName.length() < 30)
strName.append(" ");
name = strName.toString();
}
StringBuilder strPrice = new StringBuilder(args[2]); // то же самое
String price;
if (strPrice.length() > 8) {
price = strPrice.substring(0, 8);
} else {
while (strPrice.length() < 8)
strPrice.append(" ");
price = strPrice.toString();
}
StringBuilder quantity = new StringBuilder(args[3]); // то же самое
String quant;
if(quantity.length()>4){
quant = quantity.substring(0,4);
}
else
{while (quantity.length() < 4)
quantity.append(" ");
quant = quantity.toString();
}
fileOutputStream.write(("\n" + strId.toString() + name + price + quant).getBytes());
}
}
readerName.close();
fileOutputStream.close();
}
catch (Exception e){
}
}
}