How to prevent StringBuilder append() to overwrite existing content? Should I use a different buffer?
package com.codegym.task.task18.task1827;
/*
Prices
//6. The format of the new product line must precisely match that format specified in the task.
//id productName price quantity
/Users/lilianetop/Desktop/taak1827.txt
19847 Swim trunks, blue 159.00 12
198479 Swim trunks, black with printe173.00 17
19847983Snowboard jacket with reflecti10173.991234
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
public class Solution {
public static void main(String[] args) throws Exception {
//read file from console
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
reader.close();
//create a fileReader to read the file a StringBuilder to store and FileWriter to write back to file
BufferedReader input = new BufferedReader(new FileReader(fileName));
StringBuilder sb = new StringBuilder();
//create a FileWriter to write to the file
FileWriter output = new FileWriter(fileName, true);
//-c productName price quantity input from main(String[] args)
//id is 8 char and will be incremented with each new product. It will take the max value++;
int highestId = 0;
String idS = "";
String productName = ""; //30 char args[1]
String price = ""; //8 chars args[2]
String quantity = ""; //4 chars args[3]
if (args[0].equals("-c")) {
//step 1: read the file, add all its products to a buffer/StringBuilder
while (input.ready()) {
String productLine = input.readLine();
sb.append(productLine + "\n");
//step 2: find the highest idValue of all products
idS = productLine.substring(0, 8);//first 8 chars is id
int idP = Integer.parseInt(idS.trim());
if (idP > highestId) highestId = idP;
}
//step 3: add the last product to the buffer with the right padding
highestId++;
idS = String.valueOf(highestId);
String format = String.format("%-8s%-30s%-8s%-4s", idS, args[1], args[2], args[3]);
sb.append(format);
//step 4: write all the products back to the file in the proper format and add the last from main args
String[] allProducts = sb.toString().split("\n");
System.out.println(allProducts.length);
for (String product : allProducts) {
idS = product.substring(0, 8);
productName = product.substring(8, 38);
price = product.substring(38, 46);
quantity = product.substring(46);//StringIndexOutOfBoundException
String format2 = String.format("%-8s%-30s%-8s%-4s", idS, productName, price, quantity);
output.write(format2);
}
}
input.close();
System.out.println(sb.toString());//debugging the sb has correct values
output.close();
}
}