Вроде программа всё записывает как нужно, сохраняет нужное форматирование, инкрементирует id, дописывает в конец файла, что не так?
package com.javarush.task.task18.task1827;
import java.io.*;
import java.util.TreeSet;
/*
Прайсы
*/
public class Solution {
public static void main(String[] args) throws Exception {
if (args.length > 0) {
switch (args[0]) {
case ("-c"):
String fileName = getFileName();
String toWrite = getLineToWrite(args, fileName);
try (FileWriter fw = new FileWriter(fileName, true)) {
fw.write(toWrite);
} catch (IOException e) {
System.out.println("Ошибка ввода/вывода");
}
break;
default:
System.out.println("Задайте верные параметры");
break;
}
}
}
private static String getLineToWrite(String[] args, String fileName) {
String id = getID(fileName);
String productName = getProductName(args[1]);
String price = getPrice(args[2]);
String quantity = getQuantity(args[3]);
return id + productName + price + quantity + '\n';
}
private static String getQuantity(String str) {
StringBuilder strBuilder = new StringBuilder(str);
while (strBuilder.length() != 4) {
strBuilder.append(" ");
}
str = strBuilder.toString();
return str;
}
private static String getPrice(String str) {
StringBuilder strBuilder = new StringBuilder(str);
while (strBuilder.length() != 8) {
strBuilder.append(" ");
}
str = strBuilder.toString();
return str;
}
private static String getProductName(String str) {
StringBuilder strBuilder = new StringBuilder(str);
while (strBuilder.length() != 30) {
strBuilder.append(" ");
}
str = strBuilder.toString();
return str;
}
private static String getFileName() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
return reader.readLine();
} catch (IOException e) {
System.out.println("Ошибка ввода/вывода");
}
return null;
}
private static String getID(String fileName) {
TreeSet<Integer> ids = new TreeSet<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
while (reader.ready()) {
String line = reader.readLine();
String id = line.substring(0, 7);
String trimmed = trimSpace(id);
ids.add(new Integer(trimmed));
}
} catch (IOException e) {
System.out.println("Ошибка ввода/вывода");
}
int nextId = ids.last() + 1;
StringBuilder sb = new StringBuilder(String.valueOf(nextId));
while (sb.length() != 8) {
sb.append(" ");
}
return sb.toString();
}
private static String trimSpace(String str) {
str = str.replaceAll("\\s+", "");
return str;
}
}