文本文件不断删除文件上的内容。我该如何解决这个问题?

Text file keeps deleting contents on the file. How do i get around this?

显示数组的代码:

int i = 0;
            
            try {
            
               File fl = new File("Product List.txt");
               
               Scanner scn = new Scanner(fl);
            
               while(scn.hasNext()) {
               
                  String productName = scn.next();
               
                  double productPrice = scn.nextDouble();
               
                  int productAmount = scn.nextInt();
               
                  product[i] = new Products(productName,productPrice,productAmount);
               
                  i = i + 1;
               
               }
            
            }
            
            catch(IOException exc) {
            
            }
//and this code to update contents

try{
         
            Formatter writer = new Formatter("Product List.txt");
            
            for(int i = 0;i < productList.length;++i) {
            
               prd.setQuantity(prd.getQuantity() - 1);
               
               writer.format(prd.getProductName(),prd.getPrice(),prd.getQuantity(),"\n");
            
            }
         
            writer.close();
         
         }
         
         catch(IOException exc){
         
         }
每次我 运行 程序,它都会不断删除内容,当我到达必须更新文件内容的部分时,文件是空的。

如何解决这个 运行 时间错误?

来自 javadoc:

public Formatter(String fileName) throws FileNotFoundException Constructs a new formatter with the specified file name. The charset used is the default charset for this instance of the Java virtual machine.

The locale used is the default locale for this instance of the Java virtual machine.

Parameters: fileName - The name of the file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

所以我认为您应该将文件的所有内容加载到 stringbuilder,追加下一个内容并将其记录下来。