본문 바로가기

Language/Java

Java Input / Output Stream 을 열고 닫기

by engineer M 2019. 12. 29.

 

흔히 쓰는 Scanner.close() 를 쓰면 System.in 스트림을 다시 열 수 없다.

따라서 다음과 같은 방법으로 대체한다.

 
Console에서 얻어온 Reader 객체는 close를 해도 실제 console 을 close 하지는 않는다.
또한, Console 은 명시적으로 Console 창을 제공하는 형태에서만 얻어 올 수 있다.
만약, javaw 로 실행하고 있거나, IDE 처럼 표준 입출력을 전환해서 사용하고 있는 경우에는
System.console() 로 Reader 를 얻어올 수 없다.

 


 

import java.io.Console;
import java.util.Scanner;

/**
 * java.io.Console (jdk 1.6)
 * Invoking close() on the objects returned by the reader() and the writer() will not close the underlying stream of those objects.
 *
 * If this virtual machine has a console then it is represented by a unique instance of this class which can be obtained by invoking the  *

System.console() method. If no console device is available then an invocation of that method will return null.
 *
 */
public class SystemTest
{
 public static void main(String[] args) throws Exception
 {
  try{
   TestConsole();
   TestStandardIn();
  }catch(Exception ex){
   System.out.println(ex+"");
  }

 }

 // Scanner.close() does not really close the Console.Reader(). 
 private static void TestConsole() throws Exception
 {
  System.out.println("=======    TestConsole     =======");
  Console con = System.console(); // from jdk 1.6
  Scanner scan = new Scanner(con.reader());
  
  System.out.println(scan.nextLine());
  // close scanner
  con.reader().close();
  scan.close();
  System.out.println(" Scanner = " + scan.hashCode());
  System.out.println(" Scanner = " + scan);
  System.out.println("======= Scanner closed. =======");


  System.out.println("======= Scanner recreate. =======");
  scan = new Scanner(con.reader());
  System.out.println(" Scanner = " + scan.hashCode());
  System.out.println(" Scanner = " + scan);
  System.out.println(scan.nextLine());

 }

 // Scanner.close() at last closes the System.in stream.
 private static void TestStandardIn()
 {
  System.out.println("=======    TestConsole     =======");
  Scanner scan = new Scanner(System.in);
  
  System.out.println(scan.nextLine());
  // close scanner
  scan.close();
  System.out.println(" Scanner = " + scan.hashCode());
  System.out.println(" Scanner = " + scan);

  System.out.println("======= Scanner recreate. =======");
  System.out.println(" System.in = " + System.in);
  scan = new Scanner(System.in);
  System.out.println(scan.nextLine());
 }
}
[출처] [Java] Scanner 에 Console 사용해서 close 후에 다시 Scanner 생성|작성자 shwsun

 

 

댓글