简体   繁体   English

Java缓冲的作家不会写所有数据

[英]Java buffered writer wont write all data

public static void save() 
{
    BufferedWriter out = null;
    try 
    {
        out = new BufferedWriter(new OutputStreamWriter(Gdx.files.external(file).write(false)));
        out.write(Double.toString(FinanceSystem.currentPlayerCash));
        out.write("\n");
        out.write(Integer.toString(DateSystem.day));
        out.write("\n");
        out.write(Integer.toString(DateSystem.month));
        out.write("\n");
        out.write(Integer.toString(DateSystem.year));
        out.write("\n");
        for(int i = 0; i <= InventorySystem.drugsOwned.size(); i++)
            out.write(Integer.toString(InventorySystem.drugsOwned.get(i))+"\n");
        for(int i = 0; i <= AttributeSystem.attributeNames.length; i++)
            out.write(Integer.toString(AttributeSystem.attributeValues.get(i)) + "\n");



    } 
    catch (Throwable e) {} 
    finally 
    {
       try
       {
          if (out != null)
               out.close();
       } 
       catch (IOException e) {}
    }

My problem is that after the for loop for the inventory system.drugsowned nothing else gets wrote to file. 我的问题是在清单系统的for循环之后。drugsown没有其他东西写入文件。 So in this example AttributeSystem.attributeValues doesnt get wrote. 因此,在此示例中AttributeSystem.attributeValues不会被写入。 I have also tried putting other things to be wrote after this loop including non loop things and they also haven't wrote. 我还尝试过将其他要写的东西放在此循环之后,包括非循环的东西,它们也没有写。 Whagwaan? 华格安?

This is the problem: 这就是问题:

for(int i = 0; i <= InventorySystem.drugsOwned.size(); i++)
    out.write(Integer.toString(InventorySystem.drugsOwned.get(i))+"\n");

The <= should be a < . <=应该是< So if there are 5 items in the collection, you're asking for element 5, which is the 6th element as the index is 0-based. 因此,如果集合中有5个项目,则要求元素5,这是第6个元素,因为索引基于0。 That will throw an exception. 这将引发异常。

That's then getting masked by this: 然后被这个蒙住了:

catch (Throwable e)
{
}

You're completely hosing yourself here in terms of diagnostics: 您将在诊断方面完全自已:

  • Unless you can really handle an exception, don't catch it - or catch it and then rethrow it after logging (or whatever) 除非您真的能够处理异常,否则不要捕获它-或捕获它,然后在记录(或其他任何东西)后将其重新抛出
  • Catch specific exceptions wherever you can. 尽可能捕获特定的异常。 (Catching Exception is bad; catching Throwable is worse.) (捕获Exception很糟糕;捕获Throwable更糟糕。)
  • Silently catching without even logging is a terrible idea. 静默捕捞而没有伐木是一个可怕的主意。 That means you have no idea how often you've got problems, or what they were. 这意味着您不知道遇到问题的频率或发生的原因。

(Additionally, the code suggests you're either overusing static variables, or you need to sort out your naming conventions. That's a different matter though.) (此外,该代码建议您要么过度使用静态变量,要么需要整理命名约定。但这是另一回事。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM