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

u5rb5r59  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(147)

我尝试在vehicle.csv中输入一辆汽车的soldPrice。这是我为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();
    }
}

字符串
当我为其中一辆汽车输入soldPrice时,它在csv文件中变得有点混乱。我修改的vehicle soldPrice下的行上升了,我改变了soldPrice旁边的行。混乱行的carPlate也变成了soldPrice,并受到我输入的金额的影响。
如果我输入10作为售价,而不是

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


它成为

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


我在soldPrice中添加的0越多,三菱的carPlate被删除的越多。我可以做些什么来确保csv文件正常工作。

isr3a4wc

isr3a4wc1#

要解决此问题,应在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());

**更新:**在提供的代码中,当替换字符串的长度与文件中的原始字符串的长度不同时,存在问题。当使用writeBytes()函数写入“updatedLine”时,随着“sold price”中的位数增加,它会覆盖下一行的长度,即“original line”与“updatedLine”的长度之差。要正确更新文件,可以根据需要检查以下代码。

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");
        boolean found = false;

        while (raf.getFilePointer() < raf.length()) {
            String line = raf.readLine();
            String[] vehicleData = line.split(",");
            if (carPlate.equals(vehicleData[0])) {
                found = true;
                break;
            }
        }

        if (found == true) {
            File tmpFile = new File("temp.txt");
            RandomAccessFile tmpraf
                = new RandomAccessFile(tmpFile, "rw");

            raf.seek(0);
            while (raf.getFilePointer()
                   < raf.length()) {
                String updatedLine = raf.readLine();
                String[] vehicleData = updatedLine.split(",");
                if (carPlate.equals(vehicleData[0])) {
                    final int CARSTATUS = 0;
               
                    System.out.print("Please enter car sold price: ");
                    String soldPrice = input.nextLine();

                    updatedLine  = carPlate + ","
                    + vehicleData[1] + ","
                    + vehicleData[2] + ","
                    + CARSTATUS + ","
                    + soldPrice;
                 }                                                                                                              
                 tmpraf.writeBytes(updatedLine);                                
                 tmpraf.writeBytes(System.lineSeparator());
            }

            raf.seek(0);
            tmpraf.seek(0);
        
            while (tmpraf.getFilePointer()
                   < tmpraf.length()) {
                raf.writeBytes(tmpraf.readLine());
                raf.writeBytes(System.lineSeparator());
            }
            raf.setLength(tmpraf.length());

            tmpraf.close();
            raf.close();

            tmpFile.delete();
        }                     
        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();
    }
}

相关问题