Все работает, все закрывается. Валидатор врет!
package com.javarush.task.task18.task1827;
import java.io.*;
import java.util.*;
import java.lang.*;
/*
Прайсы
*/
//TODO Validator
public class Solution {
public static void main(String[] args) throws Exception {
if (args.length >= 4 && args[0].equals("-c"))
try (ProductsContainer productsContainer = new ProductsContainer(new Scanner(System.in).nextLine())) {
productsContainer.add(new Product(args[1],
args[2],
args[3]));
}
}
static class Product {
private static final int ID_LEN = 8;
private static final int NAME_LEN = 30;
private static final int PRICE_LEN = 8;
private static final int QUANTITY_LEN = 4;
String id;
String name;
String price;
String quantity;
public Product(String productDescription) {
id = productDescription.substring(0, ID_LEN).trim();
name = productDescription.substring(ID_LEN, ID_LEN + NAME_LEN).trim();
price = productDescription.substring(ID_LEN + NAME_LEN, ID_LEN + NAME_LEN + PRICE_LEN).trim();
quantity = productDescription.substring(ID_LEN + NAME_LEN + PRICE_LEN).trim();
}
public Product(String name, String price, String quantity) {
this.id = "0";
this.name = name;
this.price = price;
this.quantity = quantity;
}
public Long getID() {
return Long.parseLong(id);
}
void setID(Long newID) {
id = String.valueOf(newID);
}
@Override
public String toString() {
return String.format("%1$-" + ID_LEN + "s", id) +
String.format("%1$-" + NAME_LEN + "s", name) +
String.format("%1$-" + PRICE_LEN + "s", price) +
String.format("%1$-" + QUANTITY_LEN + "s", quantity);
}
}
static class ProductsContainer extends HashMap<Long, Product> implements Closeable {
String fileDB;
Long maxInitial = 0L;
public ProductsContainer(String fileDB) throws IOException {
this.fileDB = fileDB;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileDB)));
add(new Product(br.readLine()));
maxInitial = keySet().stream().max(Long::compare).orElse(0L);
}
void add(Product p) {
Optional<Long> max = keySet().stream().max(Long::compare);
if (0L == p.getID())
p.setID(max.orElse(0L) + 1);
put(p.getID(), p);
}
@Override
public void close() throws IOException {
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileDB, true)))) {
keySet().stream().filter(s -> s.compareTo(maxInitial) > 0).forEach(toWrite -> {
try {
bw.write("\n" + get(toWrite).toString());
} catch (IOException e) {
}
});
bw.close();
} catch (IOException e) {
throw e;
}
}
}
}