Hi
I don't understand where the problem is. When I update the data, the new data is on the same line in the file as before.
package com.codegym.task.task18.task1828;
/*
Prices 2
*/
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
public class Solution {
public static HashMap<Integer, String[]> productList = new HashMap<>();
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
reader.close();
BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = fileReader.readLine()) != null) {
int ID = Integer.parseInt(line.substring(0, 8).trim());
String[] productInfo = new String[]{line.substring(8, 38).trim(), line.substring(38, 46).trim(), line.substring(46).trim()};
productList.put(ID, productInfo);
}
fileReader.close();
if (args.length > 0) {
if (args[0].equals("-d")) {
deleteProduct(Integer.parseInt(args[1]));
writeToFile(fileName);
}
if (args[0].equals("-u")) {
int ID = Integer.parseInt(args[1]);
String productName = args[2];
String price = args[3];
String quantity = args[4];
updateProduct(ID, productName, price, quantity);
writeToFile(fileName);
}
}
}
public static void writeToFile(String fileName) throws IOException {
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(fileName));
int count = 0;
for (int id : productList.keySet()) {
String product = createProductInfo(id, productList.get(id)[0], productList.get(id)[1], productList.get(id)[2]);
if(count == productList.size() - 1){
fileWriter.write(product);
}else {
fileWriter.write(product);
fileWriter.newLine();
}
count++;
}
fileWriter.close();
}
public static String createProductInfo(int id, String productName, String price, String quantity) {
return String.format("%-8s%-30s%-8s%-4s", id, productName, price, quantity);
}
public static void updateProduct(int id, String productName, String price, String quantity) {
String[] products = {productName, price, quantity};
productList.replace(id, products);
}
public static void deleteProduct(int id) {
productList.remove(id);
}
}