Code is working ok.
package com.codegym.task.task18.task1828;
/*
Prices 2
*/
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws IOException {
String fileName;
if (args.length == 0) return;
else {
Scanner sc = new Scanner(System.in);
fileName = sc.nextLine();
sc.close();
if (args[0].equals("-u")) {
String id = args[1];
String product = args[2];
String price = args[3];
String qty = args[4];
updateProduct(fileName, id, product, price, qty);
}
if (args[0].equals("-d")) {
String id = args[1];
deleteProduct(fileName, id);
}
}
}
private static void deleteProduct(String fileName, String id) throws IOException {
String fixId = fixedLengthString(id, 8);
ArrayList<String> listFromFile = new ArrayList<>();
BufferedReader input = new BufferedReader(new FileReader(fileName));
String line;
while ((line = input.readLine()) != null) {
listFromFile.add(line);
}
input.close();
BufferedWriter output = new BufferedWriter(new FileWriter(fileName));
for (int i = 0; i < listFromFile.size(); i++) {
if (listFromFile.get(i).substring(0, 8).equals(fixId)) continue;
output.write(listFromFile.get(i));
if (i < listFromFile.size()-1) output.newLine();
}
output.close();
}
private static void updateProduct(String fileName, String id, String product, String price, String qty) throws IOException {
String fixId = fixedLengthString(id, 8);
String stringToWrite = fixId + fixedLengthString(product, 30) +fixedLengthString(price, 8) +
fixedLengthString(qty, 4);
BufferedReader input = new BufferedReader(new FileReader(fileName));
int setCursor = 0;
String line;
while (null != (line = input.readLine())) {
if (line.substring(0, 8).equals(fixId)) break;
setCursor += line.length()+2; // RandomAccess probably counts /r/n therefore +2
}
input.close();
RandomAccessFile output = new RandomAccessFile(fileName, "rw");
output.seek(setCursor);
output.write(stringToWrite.getBytes());
output.close();
}
private static String fixedLengthString(String string, int length) {
if (string.length() == length) return string;
else if (string.length() > length) return string.substring(0, length);
return String.format("%-"+ length + "s", string);
}
}