使用随机访问文件更改 csv 文件中的值时出错

问题描述 投票:0回答:1

我正在尝试将已售汽车的已售价格放入vehicle.csv 中。这是我制作的 VehicleData 类的方法。

csv文件有五列,分别是carPlate、carModel、acquiredPrice、carStatus(1表示未售出,0表示已售出)和soldPrice。

public static void updateVehicleData() {
    Scanner input = new Scanner(System.in);

    
    System.out.print("Please enter car number plate: ");
    String carPlate = input.nextLine();

    try {
        RandomAccessFile raf = new RandomAccessFile("vehicle.csv", "rw");

        while (raf.getFilePointer() < raf.length()) {
            long currentPosition = raf.getFilePointer();
            String line = raf.readLine();
            String[] vehicleData = line.split(",");

            // If the carPlate matches, update this row
            if (carPlate.equals(vehicleData[0])) {
                final int CARSTATUS = 0;
                System.out.print("Please enter car sold price: ");
                String soldPrice = input.nextLine();

                // Create a new line with updated data
                String updatedLine = carPlate + ","
                        + vehicleData[1] + "," // Assuming you want to keep the car model
                        + vehicleData[2] + "," // Assuming you want to keep the acquired price
                        + CARSTATUS + ","
                        + soldPrice;

                // Move the pointer to the beginning of the line
                raf.seek(currentPosition);

                // Write the updated line, padding with spaces if needed
                raf.writeBytes(String.format("%-" + line.length() + "s", updatedLine));

                // Move the pointer to the end of the line
                raf.seek(currentPosition + line.length());

                raf.close();
                break;
            }
        }
        System.out.println("Successfully updated the vehicle data in vehicle.csv file.");

    } catch (IOException e) {
        System.out.println("An error occurred while updating vehicle data in vehicle.csv file.");
        e.printStackTrace();
    }
}

当我输入其中一辆车的销售价格时,csv 文件中的内容变得有点混乱。我修改的车辆 sellPrice 下方的行上升,位于我更改的 sellPrice 旁边。乱七八糟的一排车牌也变成了soldPrice,并受我投入的金额影响。

如果我输入 10 作为售价,而不是

...
PQR789,Chevrolet,121200,0,10
RST901,Mitsubishi,136700,0,153000
...

变成了

...
PQR789,Chevrolet,121200,0,10ST901,Mitsubishi,136700,0,153000
...

我在soldPrice中添加的0越多,三菱的车牌被删除的就越多。我该怎么做才能确保 csv 文件正常工作。

java csv randomaccessfile
1个回答
0
投票

要解决此问题,应在 CSV 文件中写入行后添加行分隔符。在提供的代码中,这行代码

raf.writeBytes(System.lineSeparator());

应该在这行代码之后使用

raf.writeBytes(String.format("%-" + line.length() + "s", updatedLine));

所以,代码如下:

raf.writeBytes(String.format("%-" + line.length() + "s", updatedLine));
raf.writeBytes(System.lineSeparator());
© www.soinside.com 2019 - 2024. All rights reserved.