setOut(), setErr(), setIn() 명령어를 통하면 입출력을 콘솔 이외에 다른 입출력 대상으로 변경할 수 있다.
static void setOut(PrintStream out) //System.out의 출력을 지정된 PrintStream으로 변경
static void setErr(PrintStream out) //System.err의 출력을 지정된 PrintStream으로 변경
static void setIn(InputStream out) //System.in의 출력을 지정된 InputStream으로 변경
하지만 JDK1.5부터 Scanner클래스가 제공되면서 System.in으로 데이터를 받는 것이 편리해졌다.
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); //출력 대상을 test.txt로 변경
} catch(FileNotFoundException e){
System.err.println("File not found");
}
System.out.println("Hello by System.out"); //test.txt에서만 출력
System.err.println("Hello by System.err"); //콘솔에서 출력
}
}
만약 콘솔 창에서 파일 실행 시 java “실행 클래스명” > “파일명”을 입력할 시에도 출력 위치를 조정할 수 있다. 이 때 기존의 동일명의 파일이 존재할 경우 기존 내용은 삭제된다.
콘솔 창에서 java “실행 클래스명” >> “파일명”을 입력한 경우에는 마지막에 새로운 내용이 추가된다.
콘솔 창에서 java “실행 클래스명” < “파일명”을 입력한 경우에는 표준 입력을 해당 파일로 지정한다.