简体   繁体   中英

Can't close my file

I used Formatter to create my file, and when I try to close it the finally block it says instance variable hasn't been initialized, however it works if I close it in my try block, but I don't want to do that. Also, side note, I don't know if I am using my exceptions correctly either because I don't know what two of them are.

public class NewFile
{
 public static void main(String[] args)
 {

final Formatter file;

    try// create file
    {
    file = new Formatter("Records.txt");

     Account[] records = new Account[4];

      records[ 0 ] = new Account( 100, "January", "Smith", 34.56 );
      records[ 1 ] = new Account( 200, "Sally", "Anderson", 467.10 );
      records[ 2 ] = new Account( 300, "Joe", "Wright", -67.60 );
      records[ 3 ] = new Account( 400, "Henry", "Hein", 0.00 );


   for(Account display : records)
       {
      file.format("\n %d %s %s %,.2f\n", display.getAccount(),display.getFirst(), display.getLast(), display.getBalance());
   }
    }

   catch(FileNotFoundException fileNotFoundException)
    {
      System.err.println("File not found.");
    }
      catch(SecurityException securityException)
    {
      System.err.println("Do not have required permission.");
    }

       catch(FormatterClosedException formatterClosedException)
    {
      System.err.println("File is already closed.");
    }

    catch(IllegalStateException illegalStateException)
    {
      System.err.println("Error reading from file.");
    }

    finally//close the file
    {
    file.close();
    }
 }

Ok here is what I have now after comments:

import java.util.Formatter;
import java.io.FileNotFoundException;
import java.lang.IllegalStateException;
import java.lang.SecurityException;
import java.util.FormatterClosedException;

public class NewFile
{
 public static void main(String[] args)
 {

 Formatter file;

    try// create file
    {
    file = new Formatter("Records.txt");

     Account[] records = new Account[4];

      records [ 0 ] = new Account( 100, "January", "Smith", 34.56 );
      records[ 1 ] = new Account( 200, "Sally", "Anderson", 467.10 );
      records[ 2 ] = new Account( 300, "Joe", "Wright", -67.60 );
      records[ 3 ] = new Account( 400, "Henry", "Hein", 0.00 );


   for(Account display : records)
       {
      file.format("\n %d %s %s %,.2f\n", display.getAccount(),display.getFirst(), display.getLast(), display.getBalance());
   }
    }

   catch(FileNotFoundException fileNotFoundException)
    {
      System.err.println("File not found.");
    }
      catch(SecurityException securityException)
    {
      System.err.println("Do not have required permission.");
    }

       catch(FormatterClosedException formatterClosedException)
    {
      System.err.println("File is already closed.");
    }

    catch(IllegalStateException illegalStateException)
    {
      System.err.println("Error reading from file.");
    }

    finally//close the file
    {
      if(file != null)
      {
    file.close();
      }
    }
    }
 }

And this is the error: variable file might not have been initialized

Simply change final Formatter file; to

Formatter file = null;

Note that I don't believe that can be final for this to work, but this way, the compiler will see that the file variable will been initialized to something.

Then in finally, check for null:

finally {
   if (file != null) {
      file.close();
   }
}

Edit
Or as per MadProgrammer, use Java 7's try with resources.

try (Formatter file = new Formatter("Records.txt")) {
    // do stuff with file here

} catch(FileNotFoundException fileNotFoundException) {
      System.err.println("File not found.");
} catch(SecurityException securityException) {
      System.err.println("Do not have required permission.");
} catch(FormatterClosedException formatterClosedException) {
      System.err.println("File is already closed.");
} catch(IllegalStateException illegalStateException) {
      System.err.println("Error reading from file.");
}

This code compiles for me (I had to fudge the Account class):

public class NewFile
{
    public static void main(String[] args)
    {
        Formatter file = null;
        try
        // create file
        {
            file = new Formatter("Records.txt");

            Account[] records = new Account[4];

            records[0] = new Account(100, "January", "Smith", 34.56);
            records[1] = new Account(200, "Sally", "Anderson", 467.10);
            records[2] = new Account(300, "Joe", "Wright", -67.60);
            records[3] = new Account(400, "Henry", "Hein", 0.00);

            for (Account display : records)
            {
                file.format("\n %d %s %s %,.2f\n", display.getAccount(), display.getFirst(), display.getLast(),
                            display.getBalance());
            }
        }

        catch (final FileNotFoundException fileNotFoundException)
        {
            System.err.println("File not found.");
        }
        catch (final SecurityException securityException)
        {
            System.err.println("Do not have required permission.");
        }

        catch (final FormatterClosedException formatterClosedException)
        {
            System.err.println("File is already closed.");
        }

        catch (final IllegalStateException illegalStateException)
        {
            System.err.println("Error reading from file.");
        }

        finally
        // close the file
        {
            if (file != null)
            {
                file.close();
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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