如何写入 java 中的文件?

How do you write to a file in java?

这是一个代码片段,显示我正在尝试写入文件。

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();
  }
}

尝试运行此代码时抛出的异常是:

java.util.NoSuchElementException at ReadingAndWritting.printContents(ReadingAndWritting.java:37).

我尝试了很多东西,最后只得到:文件中的 "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(?)
     }

   }