I've tested the program on the terminal, with and without arguments, and it's working fine.
Is there something I am not seeing?
Suggestions appreciated.
Thanks!
package com.codegym.task.task18.task1827;
/*
Prices
*/
import java.io.*;
import java.util.ArrayList;
public class Solution {
public static void main(String[] args) {
if (args.length == 4 && args[0].equals("-c")) {
String fileName;
String productName;
String price;
String quantity;
try(BufferedReader fileNameReader = new BufferedReader(new InputStreamReader(System.in))) {
fileName = fileNameReader.readLine();
productName = args[1];
price = args[2];
quantity = args[3];
ArrayList<String> fileContent = getFileContent(fileName);
fileContent.add(createLastLine(fileContent.get(fileContent.size() - 1), productName, price, quantity));
writeFileContent(fileContent, fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void writeFileContent(ArrayList<String> content, String fileName) {
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileName))) {
for(String line:content) {
bufferedWriter.write(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static ArrayList<String> getFileContent(String fileName) {
ArrayList<String> fileContent = new ArrayList<>();
String line;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {
while ((line = reader.readLine()) != null) {
fileContent.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return fileContent;
}
public static String createLastLine(String currentLastLine, String name, String price, String quantity) {
int id = Integer.parseInt(currentLastLine.split(" ")[0]) + 1;
String resultId = String.format("%-8d", id);
String resultName = String.format("%-30s", name);
String resultPrice = String.format("%-8s", price);
String resultQuantity = String.format("%-4s", quantity);
return resultId + resultName + resultPrice + resultQuantity;
}
}