我的扫描仪和文件出了点​​问题

时间:2014-03-16 20:23:54

标签: java file

每当我运行此方法时,它会产生一个错误,表示没有行。文件(inv.txt)是25行中的1,那么25个,每个都在一条单独的行上。

public class Inventory
{
   File inventory = new File("Resources/inv.txt");
   File db = new File("Resources/db.txt");
   FileWriter write;
   StringBuilder writethis;

   public void addItem(int item, int slot)
   {

      int i = 1;
      writethis = new StringBuilder();
      Scanner scan;
      try
      {
         scan = new Scanner(inventory);
         if (scan.hasNextLine())
         {
            while (i < slot)
               writethis.append(scan.nextLine()); // This is where it says the
                                                  // error is. For reference,
                                                  // slot is 2. It may somehow
                                                  // be making an infinite loop,
                                                  // but I don't know why it
                                                  // would.
            scan.nextLine();
            writethis.append(item);
            while (i < 24)
               writethis.append(scan.nextLine());
            System.out.println(writethis.toString());
            scan.close();
         }

         try
         {
            write = new FileWriter(inventory);
            write.write(writethis.toString());
         }
         catch (IOException e)
         {

            e.printStackTrace();
         }
      }
      catch (FileNotFoundException e)
      {
         e.printStackTrace();
      }
   }
}

1 个答案:

答案 0 :(得分:1)

这可能是因为实例变量i永远不会增加吗?

我还会关闭finally块中的数据流。