【问题标题】:How do you write to a file in java?你如何在java中写入文件?
【发布时间】:2015-11-26 20:56:41
【问题描述】:

这是一个代码 sn-p,显示我正在尝试写入文件。

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

【问题讨论】:

  • productList 是如何/在哪里初始化的?数组的大小是多少?
  • 初始化为全局变量,共有3个位置
  • 写入什么文件?此代码读取一个文件。第 37 行是哪一行?
  • 顶部的方法读取文件并将内容存储到声明为全局的对象数组中。第二种方法使用对象数组写入文件
  • 第37行是double productPrice = scn.nextDouble();

标签: java java-io


【解决方案1】:

问题似乎出在

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

   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    相关资源
    最近更新 更多