Why does my file info go missing when i use BufferedReader

32 views Asked by At

What I'm doing is that I have 3 inputs: carPlate, custId and employeeId. What I'm trying to do is update lines that I need to update based on several conditions.

This is my code to read the File, which is vehicle.csv. Basically:

BufferedReader reader = new BufferedReader(new FileReader(vehicle)); 
boolean vehicle_available = false;
while((line = reader.readLine()) != null){
    lineCounterVehicle++;
    String[] split_vehicle = line.split(",");
    if (split_vehicle[0].equals(carPlate) && split_vehicle[3].equals("1")){
        vehicle_available = true;
    }
}

if (vehicle_available == false){
    return 0;
}

//record the whole vehicle file
String[] records_vehicle = new String[lineCounterVehicle];


reader = new BufferedReader(new FileReader(vehicle));

while((line = reader.readLine()) != null){
    records_vehicle[i] = line;
    i++;
}

And this is me rewriting my file:

FileWriter writer = new FileWriter(vehicle, false);
for (i = 0; i < records_vehicle.length; i++) {
    String[] elements = records_vehicle[i].split(",");
    if (elements.length < 5) {
          elements = Arrays.copyOf(elements, 5);
    }
    if (elements[0].equals(carPlate)) {
        elements[3] = "0";
        elements[4] = salesPrice;
        writer.write(String.join(",", elements) + "\n");
    }
}

My file is CSV, which looks something like this:

carPlate,carModel,acquirePrice,carStatus,salesPrice
ABC123,Honda Civic,90000,0,95000
XYZ789,Toyota Camry,120000,0,126000
MNO456,Nissan Almera,80000,0,85600
PQR234,Mazda 3,110000,0,115600
GHI567,Ford Focus,100000,0,107620
JKL678,Chevrolet Cruze,95000,0,99750
STU901,Kia Forte,85000,0,89500
VWX234,Honda Accord,130000,0,147000
CDE345,Mitsubishi Lancer,90000,0,95550
FGH456,Nissan Sylphy,100000,0,105550
IJK567,Mazda 6,140000,0,148800
LMO678,Ford Fiesta,80000,0,85500
NOP789,Chevrolet Malibu,120000,0,127000
QRS901,Kia Optima,110000,0,113500
TUV012,Honda City,85000,0,89150
WXY123,Mitsubishi Attrage,75000,0,78050
ZAB234,Nissan Teana,130000,0,135400
CDF345,Mazda CX-5,150000,0,159900
GHI456,Ford Escape,140000,0,145670
JLM567,Chevrolet Captiva,130000,0,137000
MNO678,Ford Fiesta,80100,0,85000
PQR789,Chevrolet Malibu,121200,1,

I was expecting it to rewrite the file perfectly. While it did change the lines that I wanted to change just fine, for some reason it decides to just throw away random amounts of lines towards the end.

0

There are 0 answers