no trouble in my environnement :-/
package fr.codegym.task.task18.task1828;
/*
Tarifs 2
*/
import java.io.*;
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
public class Solution {
public String filename;
public SortedMap<Integer, String> database = new TreeMap<>();
public int maxKey = 0;
public static void main(String[] args) throws Exception {
/**
* prog arguments
* -c "asdfasfasdfasdf" "159.00" "12"
* -d 19847985
* -u 19847 "asdfasfasdfasdf" "159.00" "12"
*/
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
Solution sol = new Solution();
sol.filename = console.readLine();//"c:/temp/1828.txt";//
sol.readFile();
if (args.length == 0) return;
switch (args[0]){
case "-c":
sol.addItem(args);
sol.writeFile();
break;
case "-d":
sol.removeItem(args);
sol.writeFile();
break;
case "-u":
sol.updateItem(args);
sol.writeFile();
break;
default:
}
}
public void removeItem(String args[]) {
int id = Integer.parseInt(args[1]);
this.database.remove(id);
}
public void updateItem(String args[]) {
int id = Integer.parseInt(args[1]);
String row = this.createItemString(id, args[2], args[3], args[4] );
if( database.containsKey(id))
database.put(id,row);
}
public void addItem(String args[]) {
String row = this.createItemString(++this.maxKey, args[1], args[2], args[3] );
this.database.put(this.maxKey, row);
}
public String createItemString(int id, String nomProduit, String prix, String quantity) {
String row = "";
row += this.padding(Integer.toString(id), 8);
row += this.padding(nomProduit, 30);
row += this.padding(prix, 8);
row += this.padding(quantity, 4);
return row;
}
public String padding(String source, int size) {
//in java 11 it's simply " ".repeat(size) :-/
String padding = String.join("", Collections.nCopies(size, " "));
return (source + padding).substring(0, size);
}
public void readFile() throws IOException {
FileInputStream file = new FileInputStream(this.filename);
String[] lines = null; //used to process file content
if (file.available() > 0) {
byte[] buffer = new byte[file.available()];
file.read(buffer);
//one string per line
lines = new String(buffer).split("\\r?\\n");
}
for (String line : lines) {
int lineKey = Integer.parseInt(line.substring(0, 8).trim());
this.maxKey = this.maxKey < lineKey ? lineKey : this.maxKey;
this.database.put(lineKey, line);
}
file.close();
}
public void writeFile() throws IOException {
FileOutputStream file = new FileOutputStream(this.filename);
String[] values = this.database.values().toArray(new String[0]);
for (int i = 0; i < values.length ; i++) {
String row = values[i] + (i == values.length-1 ? "":"\n");
file.write(row.getBytes(), 0, row.getBytes().length);
}
file.flush();
file.close();
}
}