如何在java中写入文件?
这是一段代码片段,显示我试图写入文件如何在java中写入文件?,java,java-io,Java,Java Io,这是一段代码片段,显示我试图写入文件 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 productPr
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", false));
for (int i = 0; i < 2; ++i) {
writer.format(productList[i].name + "", (productList[i].price + 200.0 + ""), (productList[i].number - 1), "\n");
}
writer.close();
} catch (Exception exc) {
exc.printStackTrace();
}
}
我尝试了多种方法,但结果都是文件中的“cokefruitgushersAlnassma”。我想要的是:
coke 7.95 10
fruitgushers 98.00 6
Alnassma 9.80 7
问题似乎出在
String productName = scn.next();
// Here:
double productPrice = scn.nextDouble();
// And here:
int productAmount = scn.nextInt();
在scn.next()
之后,在请求下一个元素(分别为double或int)之前,不检查scn.hasNext()
。因此,要么您的文件不完整,要么不符合您期望的确切结构,要么您在尝试处理不存在的数据之前错过了另外两项检查
解决方案可以是:
while (scn.hasNext()) {
String productName = scn.next();
if ( scn.hasNext() ) {
double productPrice = scn.nextDouble();
if ( scn.hasNext() ) {
int productAmount = scn.nextInt();
// Do something with the three values read...
} else {
// Premature end of file(?)
}
} else {
// Premature end of file(?)
}
}
productList
是如何初始化的/在哪里初始化的?数组的大小是多少?它被初始化为一个全局变量,它有3个位置写入哪个文件?这段代码读取一个文件。第37行是什么?上面的方法读取文件并将内容存储到声明为全局的对象数组中。第二个方法使用对象数组写入文件,第37行是double-productPrice=scn.nextDouble()代码>
while (scn.hasNext()) {
String productName = scn.next();
if ( scn.hasNext() ) {
double productPrice = scn.nextDouble();
if ( scn.hasNext() ) {
int productAmount = scn.nextInt();
// Do something with the three values read...
} else {
// Premature end of file(?)
}
} else {
// Premature end of file(?)
}
}