为什么我的代码将ArrayList元素写入输出文件两次,而不是更新ArrayList?

时间:2018-02-18 04:38:54

标签: java arraylist io

我只想说谢谢你花时间研究我的问题。我目前正在开发库存界面。我遇到的问题是,当我读取更新文件时,要更新我的数据库文件,这就是我得到的:database:abc,123,10.0,5.0,false,10(partName,partNumber,listPrice,salePrice,onSale,量)

我在读取更新文件后

: abc,123,10.0,5.0,false,10是我的db中的第一个,后跟abc,123,20.0,10.0,true,2

如何修复此问题以便更新db文件中的字符串,而不是将其附加到文件中?

这是我的一些代码:

//findBp method
public static BikePart findBp(ArrayList<BikePart> bpal, BikePart bp) {
    BikePart found = null;
    for(BikePart b : bpal) {
        if(b.getPartName().equals(bp.getPartName()) && b.getPartNumber() == bp.getPartNumber()) {
            found = b;
            break;
        }
    }
    return found;
}

//sort by partName
public static void sortName(ArrayList<BikePart> bpal) {
    Collections.sort(bpal, BikePart.bpNameComp);
}
//sort by partNumber
public static void sortNumber(ArrayList<BikePart> bpal) {
    Collections.sort(bpal, BikePart.bpPartNumComp);
}

//readFile method
public static void readFile(String fileName, ArrayList<BikePart> bpal) {
    if(fileName == null || fileName.equals("")) {
        return;
    }
    File file = new File(fileName);
    try {
        Scanner read = new Scanner(file);
        while(read.hasNextLine()) {
            String line = read.nextLine();
            String pv[] = line.split(",");
            BikePart bp = BikePart.toObject(pv);
            BikePart found = findBp(bpal, bp);
            if(found == null) {
                bpal.add(bp);
            } else {
                found.setQuantity(found.getQuantity() + bp.getQuantity());
                found.setPartName(bp.getPartName());
                found.setPartNumber(bp.getPartNumber());
                found.setListPrice(bp.getListPrice());
                found.setSalesPrice(bp.getSalesPrice());
                found.setPartOnSale(bp.isPartOnSale());
            }
        }
        read.close();
    }
    catch (FileNotFoundException e) {
        System.out.println(fileName + " is not found!");
        System.out.println("Enter another file name.");
        String fileName2 = in.nextLine();
        readFile(fileName2, bpal);
    }
}
//writeFile method
public static void writeFile(String fileName, ArrayList<BikePart> bpal) {
    try {
        BufferedWriter outStream = new BufferedWriter(new FileWriter(fileName, true));
        for(BikePart bp : bpal) {
            outStream.write(bp.toString());
            outStream.newLine();
        }
        outStream.close();
    }
    catch (IOException e) {
        System.out.println("file not found!");
    }
}

public static void main(String[] args) {
    //calendar field
    Calendar cal = Calendar.getInstance();

    //ArrayList for DB
    ArrayList<BikePart> bpal = new ArrayList<BikePart>();
    readFile("DB.txt", bpal);

    //user input variable
    String usrIn = "";

    //loop for user choice
    while(usrIn != "Quit") {
        //prompts user to select choice
        System.out.println("Please select your option from "
                + "the following menu: ");
        System.out.println("Read: Read an inventory delivery file");
        System.out.println("Enter: Enter a part");
        System.out.println("Sell: Sell a part");
        System.out.println("Display: Display a part");
        System.out.println("SortName: Sort parts by part name");
        System.out.println("SortNumber: Sort parts by part number");
        System.out.println("Quit: ");
        System.out.println("Enter your choice: ");

        //initiates usrIn
        usrIn = in.nextLine();

        //switch for input choice
        switch(usrIn) {

        case "Read":
            //read method 
            System.out.println("Enter file name: ");
            String fileName = in.nextLine();
            readFile(fileName, bpal);
            break;
        case "Enter":
            //enter method
            break;
        case "Sell":
            //sell method
            break;
        case "Display":
            //display method
            break;
        case "SortName":
            //sortName method
            break;
        case "SortNumber":
            //sortNum method
            break;
        case "Quit":
            //quit method
            writeFile("DB.txt", bpal);
            System.out.println("good bye! ");
            break;
        }
        if(usrIn.equals("Quit")) {
            break;
        }
    }

}

我还没有填写剩下的代码,因为我想在继续之前先解决这个问题。我只是想再次感谢你看一看。

2 个答案:

答案 0 :(得分:0)

因为您要附加到文件:

new FileWriter(fileName, true)

这就是true参数的作用。

答案 1 :(得分:-1)

为了替换文件中的数据,您必须阅读它,替换数据并写出新数据。

执行此操作的一种方法如this answer中所示。以下简要概述:

    // Read all the data
    BufferedReader file = new BufferedReader(new FileReader("data.txt"));
    String line;
    StringBuffer inputBuffer = new StringBuffer();

    while ((line = file.readLine()) != null) {
        inputBuffer.append(line);
        inputBuffer.append('\n');
    }
    String inputStr = inputBuffer.toString();

    file.close();

   // Replace your string code goes here.....

  // Then write all the updated data back

    FileOutputStream fileOut = new FileOutputStream("notes.txt");
    fileOut.write(inputStr.getBytes());
    fileOut.close();

关于重复:

可能是您更新ArrayList的方式。我是否可以建议您在写入文件之前打印列表以检查它是否不是重复条目?如果是,那么它不是文件写入问题而是数据更新问题。然后,您必须确保更新列表中的BikePart,而不是再次添加。