I did a few tests and it seems to be working fine but it fails one of the tests..
package com.codegym.task.task18.task1827;
/*
Prices
*/
import java.io.*;
import java.util.ArrayList;
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
if ((args.length > 1) && args[0].equals("-c")) {
String fileName = reader.readLine();
addProduct(fileName, args[1], args[2], args[3]);
}
}
public static void addProduct(String fileName, String productName, String price, String quantity) throws IOException {
FileOutputStream outputStream = new FileOutputStream(fileName, true);
String id = getId(fileName);
StringBuilder idStr = new StringBuilder(getId(fileName));
StringBuilder productStr = new StringBuilder(productName);
StringBuilder priceStr = new StringBuilder(price);
StringBuilder quantityStr = new StringBuilder(quantity);
if (id.length() < 8) {
for (int i = id.length(); i < 8; i++) {
idStr.append(" ");
}
} else idStr.setLength(8);
if (productName.length() < 30) {
for (int i = productName.length(); i < 30; i++) {
productStr.append(" ");
}
} else productStr.setLength(30);
if (price.length() < 8) {
for (int i = price.length(); i < 8; i++) {
priceStr.append(" ");
}
} priceStr.setLength(8);
if (quantity.length() < 4) {
for (int i = quantity.length(); i < 4; i++) {
quantityStr.append(" ");
}
}quantityStr.setLength(4);
String productLine = idStr.toString() + productStr.toString() + priceStr.toString() + quantityStr.toString();
outputStream.write(productLine.getBytes());
outputStream.close();
}
public static String getId(String fileName) throws IOException {
int id = 1;
FileInputStream inputStream = new FileInputStream(fileName);
BufferedReader lineReader = new BufferedReader(new InputStreamReader(inputStream));
ArrayList<String> lines = new ArrayList<>();
String data;
while ((data = lineReader.readLine()) != null) {
lines.add(data);
}
lineReader.close();
inputStream.close();
if (!lines.isEmpty()) {
id = Integer.parseInt(lines.get(lines.size()-1).substring(0, 8).trim()) + 1;
return String.valueOf(id);
}
return String.valueOf(id);
}
}