Please help me out here. This task is about to drive me insane! Thanks to any suggestions!
package com.codegym.task.task18.task1827;
/*
Prices
*/
import javax.sound.midi.Soundbank;
import java.io.*;
public class Solution {
public static void main(String[] args) throws Exception {
final int idLength = 8;
int idMax = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = br.readLine();
br.close();
// this is just for testing: args.length>0 args[0].equals("-c")
// String fileName = "/home/sven/coding/crudTask.txt";
// String name = "hallo Test";
// String price = "23.84";
// String quantity = "3";
if(args.length>0){
FileInputStream inputStream = new FileInputStream(fileName);
FileOutputStream outputStream;
String name = args[1];
String price = args[2];
String quantity = args[3];
if(args[0].equals("-c")){
try (BufferedReader br2 = new BufferedReader(new FileReader(new File(fileName)))){
String line;
// find the maximum of Ids
while ((line = br2.readLine()) != null){
String nums = line.substring(0, idLength);
int id = Integer.parseInt(nums.trim());
if(id > idMax) idMax = id;
}
idMax++;
// put the data of the file in a buffer and put it to the outputstream:
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
outputStream = new FileOutputStream(fileName);
outputStream.write(buffer);
// create the new line to add to the file with string.format
String num = Integer.toString(idMax);
String value = String.format("%1$-8s%2$-30s%3$-8s%4$-4s",num, name, price, quantity);
// we might need to add a new line first
// outputStream.write('\n');
for(char x : value.toCharArray()){
outputStream.write(x);
}
outputStream.close();
inputStream.close();
}catch (Exception e){
System.out.println("Exception found");
e.printStackTrace();
}
}
}
}
}