2012-07-24 11 views
5

Ho la seguente classe Java che fa una cosa, spara i valori da config.properties.devo circondare fileInputStream.close con un blocco try/catch/finally? Com'è fatto?

Quando arriva il momento di chiudere il fileInputStream, penso di leggere su Wikipedia che è bello averlo in un blocco finale. Perché funziona onestamente bene nel blocco try/catch.

Puoi mostrarmi la correzione per ottenere fileInputStream.close() in una sezione finale?

ConfigProperties.java base del pacchetto;

import java.io.FileInputStream; 
import java.util.Properties; 

public class ConfigProperties { 

    public FileInputStream fileInputStream; 
    public String property; 

    public String getConfigProperties(String strProperty) { 

     Properties configProperties = new Properties(); 
     try { 

      fileInputStream = new FileInputStream("resources/config.properties"); 
      configProperties.load(fileInputStream); 
      property = configProperties.getProperty(strProperty); 
      System.out.println("getConfigProperties(" + strProperty + ")"); 

      // use a finally block to close your Stream. 
      // If an exception occurs, do you want the application to shut down? 

     } catch (Exception ex) { 
      // TODO 
      System.out.println("Exception: " + ex); 
     } 
     finally { 
      fileInputStream.close(); 
     } 

     return property; 
    } 
} 

La soluzione è solo quella di fare come suggerisce Eclipse e farlo nel blocco finale?

finally { 
    try { 
     fileInputStream.close(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

Grazie a tutti!

+1

FYI: commons-io ha una buona funzione: IOUtils.closeQuietly() che si prenderà cura del try/catch sulla chiusura. Il tuo codice sembrerà molto più carino :) Tieni presente che questa funzione non ti dà la possibilità di rispondere all'IOException, ma di solito le persone non lo fanno e ignorano comunque l'eccezione. Se devi rispondere, crea il tuo metodo di utilità che registra o stampa una traccia dello stack o qualsiasi altra cosa tu debba fare. – Matt

risposta

7

Perché FileInputStream.close() genera IOException e infine il blocco {} non rileva eccezioni. Quindi è necessario prenderlo o dichiararlo per compilare. Il suggerimento di Eclipse va bene; cattura IOException all'interno del blocco finally {}.

+0

È inoltre possibile utilizzare [IOUtils.closeQuietly()] (http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/IOUtils.html#closeQuietly (java.io.Closeable)) metodo da Commons IO. Include il metodo close per eliminare tutte le eccezioni IOException generate. Più pulito di avere un altro try/catch block. –

11

Sì, questa è la soluzione pre-Java 7 comune. Tuttavia, con l'introduzione di Java 7, ora ci sono try-with-resource dichiarazioni che si chiude automaticamente tutte le risorse dichiarate quando le uscite try blocchi:

try (FileInputStream fileIn = ...) { 
    // do something 
} // fileIn is closed 
catch (IOException e) { 
    //handle exception 
} 
7

L'approccio standard è:

FileInputStream fileInputStream = null; 
try { 
    fileInputStream = new FileInputStream(...); 
    // do something with the inputstream 
} catch (IOException e) { 
    // handle an exception 
} finally { // finally blocks are guaranteed to be executed 
    // close() can throw an IOException too, so we got to wrap that too 
    try { 
     if (fileInputStream != null) { 
      fileInputStream.close(); 
     }   
    } catch (IOException e) { 
     // handle an exception, or often we just ignore it 
    } 
} 
Problemi correlati