Инициализация файла проходит с самого начала (т.е. пустого)
package com.javarush.task.task18.task1827;
/*
Прайсы
*/
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
reader.close();
try {
if ("-c".equals(args[0])) {
addGoods(args[1], args[2], args[3], fileName);
}
}
catch (ArrayIndexOutOfBoundsException ex){
}
}
private static void addGoods(String arg, String arg1, String arg2, String fileName) {
String id8 = "0";
String productName30 = arg;
String price8 = arg1;
String quantity4 = arg2;
String updateStr = String.format("%-8s%-30s%-8s%-4s\n", id8,productName30,price8,quantity4);
int nextIndex;
List<String> list = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
String str;
while ((str = reader.readLine()) != null){
list.add(str);
}
if (!list.isEmpty()){
nextIndex = findMaxIndex(list) + 1;
updateStr = String.format("%-8d%-30s%-8s%-4s\n", nextIndex,productName30,price8,quantity4);
}
reader.close();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, true)));
writer.write(updateStr);
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static int findMaxIndex(List<String> list) {
int maxId = 0;
for (int i = 0; i < list.size(); i++) {
int buff = Integer.parseInt(list.get(i).substring(0,8).trim());
if (buff > maxId) maxId = buff;
}
return maxId;
}
}