我在这里声明了一个数组和变量。产品列表数组,名称,价格和数量
import java.io.*;
import java.util.*;
public class ReadingAndWritting {
public String name;
public double price;
public int number;
public ReadingAndWritting[] productList = new ReadingAndWritting[3];
public ReadingAndWritting() {
}
public ReadingAndWritting(String name, double price, int number) {
this.name = name;
this.price = price;
this.number = number;
}
public void printContents() {
int i = 0;
try {
FileReader fl = new FileReader("Product List.txt");
Scanner scn = new Scanner(fl);
while (scn.hasNext()) {
String productName = scn.next();
double productPrice = scn.nextDouble();
int productAmount = scn.nextInt();
System.out.println(productName + " is " + productPrice + " pula. There are " + productAmount + " items left in stalk.");
productList[i] = new ReadingAndWritting(productName, productPrice, productAmount);
i = i + 1;
}
scn.close();
} catch (IOException exc) {
exc.printStackTrace();
} catch (Exception exc) {
exc.printStackTrace();
}
}
public void writeContents() {
try {
//FileOutputStream formater = new FileOutputStream("Product List.txt",true);
Formatter writer = new Formatter(new FileOutputStream("Product List.txt", true));
for (int i = 0; i < productList.length; ++i) {
writer.format(name, (price + 100.0), (number - 1), "\n");
}
writer.close();
} catch (IOException exc) {
exc.printStackTrace();
}
}
public static void main(String[] args) {
ReadingAndWritting obj = new ReadingAndWritting();
System.out.println("_____THIS IS THE BEGINNING OF THE PRODUCT LIST_____");
obj.printContents();
System.out.println("_____THIS IS THE END OF THE PRODUCT LIST_____");
System.out.println("_____THIS IS THE BEGINNING OF THE PRODUCT LIST_____");
obj.writeContents();
obj.printContents();
System.out.println("_____THIS IS THE END OF THE PRODUCT LIST_____");
}
}
每次我运行代码时,它都会不断格式化现有文件,然后报告 NullPointerException。我完全不知道如何解决这个问题,而且我们的讲师从未介绍过它。请
block 引用>the productList[] array has name,price and number value contained in each identifier. I want to wipe the contents of the existing file and then write with the new values to update contents from the array
最佳答案
您使用的构造函数会截断输入文件,如 Javadoc 中明确所述:
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.
您可以使用其他构造函数,例如 Formatter(OutputStream os)
来避免截断。
Formatter writer = new Formatter(new FileOutputStream("Product List.txt",true));
至于NullPointerException
,请参阅您的评论:
public String name;
name
未初始化,因此默认为 null
,这会导致 NullPointerException
。
附注我不知道 productList
是什么,根据它的名称以及您正在迭代它的事实,也许您应该获得 price
和 name
来自该列表的元素。
编辑:
根据代码的其余部分,您应该从 productList
数组中获取值:
for (int i = 0; i < productList.length; ++i) {
writer.format(productList[i].name, (productList[i].price + 100.0), (productList[i].number - 1), "\n");
}
关于java - 此代码不断格式化文件而不是写入文件。我如何解决它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33937451/