2011-11-10 17 views
14

estoy usando FileOutputStream con PrintStream así:¿Debo cerrar FileOutputStream, que está incluido en PrintStream?

class PrintStreamDemo { 
    public static void main(String args[]){ 
    FileOutputStream out; 
    PrintStream ps; // declare a print stream object 
    try { 
    // Create a new file output stream 
    out = new FileOutputStream("myfile.txt"); 

    // Connect print stream to the output stream 
    ps = new PrintStream(out); 

    ps.println ("This data is written to a file:"); 
    System.err.println ("Write successfully"); 
    ps.close(); 
    } 
    catch (Exception e){ 
    System.err.println ("Error in writing to file"); 
    } 
    } 
} 

Im sólo el cierre PrintStream. ¿Debo cerrar también el FileOutputStream (out.close();)?

+0

Echa un vistazo al código fuente: http://www.docjar.com/html/api/java/io/PrintStream.java.html – jtoberon

+0

Por cierto, la belleza de PrintStream es el hecho de que puedes usarlo solo una cadena (para el nombre de archivo) o un objeto de archivo. No necesita abrir un FOStream solo para usarlo en PrintStream. – Mechkov

Respuesta

22

No, solo tiene que cerrar la secuencia más externa. Delegará todo el camino a las transmisiones envueltas.

Sin embargo, su código contiene una falla conceptual, el cierre debe ocurrir en finally, de lo contrario, nunca se cierra cuando el código arroja una excepción entre la apertura y el cierre.

E.g.

public static void main(String args[]) throws IOException { 
    PrintStream ps = null; 

    try { 
     ps = new PrintStream(new FileOutputStream("myfile.txt")); 
     ps.println("This data is written to a file:"); 
     System.out.println("Write successfully"); 
    } catch (IOException e) { 
     System.err.println("Error in writing to file"); 
     throw e; 
    } finally { 
     if (ps != null) ps.close(); 
    } 
} 

(tenga en cuenta que he cambiado el código para tiro la excepción para que pueda entender la razón del problema, la excepción es decir, contiene información detallada sobre la causa del problema)

O , cuando ya está en Java 7, también puede utilizar ARM (Automatic Resource Management, también conocido como try-with-resources) para que no tenga que cerrar nada usted mismo:

public static void main(String args[]) throws IOException { 
    try (PrintStream ps = new PrintStream(new FileOutputStream("myfile.txt"))) { 
     ps.println("This data is written to a file:"); 
     System.out.println("Write successfully"); 
    } catch (IOException e) { 
     System.err.println("Error in writing to file"); 
     throw e; 
    } 
} 
+0

Cuando agrego finalmente bloquear e intento hacer 'ps.close()' allí obtengo un error: 'variable ps podría no haberse inicializado' – hs2d

+0

Debe inicializarlo con' null'. – BalusC

+0

¡Ah, no pensé en eso, gracias! – hs2d

3

No, de acuerdo con el javadoc, el método de cierre será close el flujo subyacente para usted.

5

No, aquí consiste en la realización de close() método PrintStream 's:

public void close() { 
    synchronized (this) { 
     if (! closing) { 
     closing = true; 
     try { 
      textOut.close(); 
      out.close(); 
     } 
     catch (IOException x) { 
      trouble = true; 
     } 
     textOut = null; 
     charOut = null; 
     out = null; 
     } 
    } 

Se puede ver que cierra out.close(); flujo de salida.

Cuestiones relacionadas