andy07070
andy07070

Reputation: 45

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. So in this example AttributeSystem.attributeValues doesnt get wrote. I have also tried putting other things to be wrote after this loop including non loop things and they also haven't wrote. Whagwaan?

Upvotes: 1

Views: 1266

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1501053

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. 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.)
  • 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.)

Upvotes: 7

Related Questions