본문 바로가기

Java 길찾기/Java의 정석

[Java] 입출력 I/O - 표준입출력의 대상변경(setOut(), setErr(), setIn())

초기에는 System.in, System.out, System.err의 입출력 대상이 콘솔화면이지만, setIn(), setOut(), setErr()를 사용하면 입출력을 콘솔 이외에 다른 입출력 대상으로 변경하는 것이 가능하다.

메서드 설명
static void setIn(InputStream in) System.in 의 입력을 지정한 InputStream으로 변경
static void setOut(PrintStream out) System.out 의 출력을 지정한 PrintStream으로 변경
static void setErr(PrintStream err) System.err의 출력을 지정한 PrintStream으로 변경

 

그러나 JDK1.5부터 Scanner클래스가 제공되면서 System.in 으로부터 데이터를 입력받아 작업하는 것이 편리해졌다.

class StandardIOEx2 {
    public static void main(String args[]) {
        System.out.println("out : Hello World!");
        System.err.println("err : Hello World!");
    }
}

System.out, System.err 모두 출력대상이 콘솔이기 때문에 System.out 대신 System.err을 사용해도 같은 결과를 얻는다.

 

import java.io.*;

class StandardIOEx3 {
    public static void main(String args[]) {
        PrintStream ps = null;
        FileOutputStream fos = null;

        try{
            fos = new FileOutputStream("test.txt");
            ps = new PrintStream(fos);
            System.setOut(ps); // System.out의 출력대상을 test.txt 파일로 변경
        } catch (FileNotFoundException e) {
            System.err.println("File not found.");
        }
        System.out.println("out : Hello World!");
        System.err.println("err : Hello World!");
    }
}

System.out의 출력소스를 test.txt 파일로 변경하였기 때문에 System.out을 이용한 출력은 모두 test.txt 파일에 저장된다. 그래서 실행결과에는 System.err를 이용한 출력만 나타난다.

setOut()과 같은 메서드를 사용하는 방법 외에도 커맨드라인에서 표준입출력의 대상을 간단히 바꿀 수 있는 다음과 같은 방법이 있다.

C:jdk17.01\work\ch15> java StandardIOEx2
out : Hello World!
err : Hello World!

 

StandardIOEx2의 System.out 출력을 콘솔이 아닌 output.txt로 지정한다. 즉, System.out에 출력하는 것은 output.txt에 저장된다. 기존에 output.txt 파일이 있었다면 기존의 내용은 삭제된다.

C:jdk17.01\work\ch15> java StandardIOEx2 > output.txt
err : Hello World!

C:jdk17.01\work\ch15> type otuput.txt
out : Hello World!

 

StandardIOEx2의 System.out 출력을 output.txt에 저장한다. '>'을 사용했을 때와는 달리 '>>'는 기존 내용의 마지막에 새로운 내용이 추가된다.

C:jdk17.01\work\ch15> java StandardIOEx2 >> output.txt
err : Hello World!

C:jdk17.01\work\ch15> type otuput.txt
out : Hello World!
out : Hello World!

 

StandardIOEx2의 표준입력을 output.txt로 지정한다. 즉, 콘솔이 아닌 output.txt로부터 데이터를 입력받는다.

C:jdk17.01\work\ch15> java StandardIOEx2 < output.txt
out : Hello World!
out : Hello World!