My testing seems to pass all validation criteria, however validation fails for:
- When the program is run with the arguments "-c productName price quantity", a new line with the corresponding product should be added to the end of the file.
- The product must have the next id after the maximum id found in the file.
- The format of the new product line must precisely match that format specified in the task.
- The file streams must be closed.
- recommendation from your mentor
- The file input stream was not closed.
I replaced try with resources solution with explicit close and that did not seem to change anything.
Any help/ideas would be greatly appreciated.
package com.codegym.task.task18.task1827;
/*
Prices
*/
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String[] args) throws Exception {
if (args.length == 0) return;
String fileName = "";
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
fileName = reader.readLine();
}
if ("-c".equalsIgnoreCase(args[0])) {
AddItem(fileName, args[1], args[2], args[3]);
}
}
private static void AddItem(String fileName, String productName, String price, String quantity) throws IOException {
File f = new File(fileName);
if (!f.isFile()) {
Files.createFile(f.toPath());
}
List<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
int maxId = 0;
boolean isMoreLines = true;
while (isMoreLines) {
String inLine = reader.readLine();
if (inLine == null ) {
break;
} else if ( "".equals(inLine)) {
isMoreLines = false;
} else {
String idString = inLine.substring(0, 8).trim();
int id = Integer.parseInt(idString);
if (id > maxId) maxId = id;
}
lines.add(inLine);
}
//add the new product
maxId++;
String id = String.format("%-8s", Integer.toString(maxId));
String line = String.format("%-8s%-30s%-8s%-4s", id,productName, price, quantity);
lines.add(line);
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))){
for (String line : lines) {
writer.write(line);
writer.newLine();
}
}
// System.out.println(line);
}
}