2017-12-01 6 views
0

다음 코드 단편이 있습니다. 코드가 잘 보이지만 화면에 Bye을 인쇄 할 수 없습니다.한 번만 인쇄 할 수있는 두 개의 PrintWriter 개체

import java.io.PrintWriter; 

public class PrintWriterTwice { 
    public static void main(String[] args) { 
    PrintWriter first = new PrintWriter(System.out); 
    first.print("Hello"); 
    first.flush(); 
    first.close(); 

    PrintWriter second = new PrintWriter(System.out); 
    second.print("Bye"); 
    second.flush(); 
    second.close(); 
    } 
} 

다음은 프로그램의 출력입니다 :

안녕하세요

내가이 동작을 얻는 이유는 알 수 있습니까?

답변

3

PrintWriterclose()을 호출하면 그 밑에있는 OutputStream (이 경우 System.out)이 닫힙니다. 그래서 당신은 더 이상 출력을 얻지 못합니다. close()을 제거하거나 second 글을 읽은 후 이동하십시오.

PrintWriter first = new PrintWriter(System.out); 
first.print("Hello"); 
first.flush(); 

PrintWriter second = new PrintWriter(System.out); 
second.print("Bye"); 
second.flush(); 
first.close(); 
second.close(); 
+0

효과가있었습니다. 나는'System.out.close()'를 시도했는데 같은 동작을 재현 할 수있었습니다. 고마워요 :) –