gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:46:14 25 4
gpt4 key购买 nike

显示数组的代码:

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.

所以我认为您应该将文件的所有内容加载到字符串生成器,附加下一个内容并将其写下来。

关于java - 文本文件不断删除文件上的内容。我该如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33911793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com