Мне нужно закрыть FileOutputStream, который завернут PrintStream?

Я использую FileOutputStream с 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 закрывает только PrintStream. Мне также нужно закрыть файл FileOutputStream (out.close();)?

Ответы

Ответ 1

Нет, вам нужно только закрыть внешний поток. Он будет делегировать весь путь к завернутым потокам.

Однако ваш код содержит один концептуальный сбой, закрытие должно происходить в finally, иначе оно никогда не закрывается, когда код генерирует исключение между открытием и закрытием.

например.

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();
    }
}

(обратите внимание, что я изменил код на бросить исключение, чтобы вы поняли причину проблемы, исключение содержит подробную информацию о причине проблемы)

Или, когда вы уже на Java 7, вы также можете использовать ARM (автоматическое управление ресурсами, также известное как try-with-resources) так что вам не нужно ничего закрывать самостоятельно:

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;
    }
}

Ответ 2

Нет, вот реализация метода PrintStream close():

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;
        }
    }

Вы можете видеть out.close();, который закрывает выходной поток.

Ответ 4

Нет, согласно javadoc, метод close close базовый поток для вас.