표준 입출력을 담당하는 System 클래스에 대해 알아보자.
System 클래스
- final 클래스로 상속 및 인스턴스를 만들 수 없음
public final class System { ... }
- 표준 입력, 표준 출력 및 오류 출력 스트림 기능이 있으며
외부에서 정의된 속성 및 환경 변수에 대한 정보 제공,
배열 일부를 빠르게 복사하기 위한 유틸리티 메소드가 있음- 별도의 스트림을 생성하는 코드를 작성하지 않아도 자동적으로 생성됨
public final static InputStream in = null;
public final static PrintStream out = null;
public final static PrintStream err = null;
PrintStream ps = null;
FileOutputStream output = null;
String filePath = "D:\\project\\workspace\\studyhalle\\src\\main\\java\\s1\\week13\\test.txt";
try {
output = new FileOutputStream(filePath);
ps = new PrintStream(output);
System.setOut(ps); // 출력대상을 파일로 변경
} catch (Exception e) {
e.printStackTrace();
}
// System.out은 파일로 대상을 변경했기 때문에 System.err 내용만 나옴
System.out.println("## System.out ##");
System.err.println("## System.err ##");
[ 실행결과 ]
## System.err ##
int[] tmpArr = { 1, 10, 100, 1000, 2, 20, 200, 2000 };
// int배열의 데이터를 txt에 저장한 다음 출력함
String filePath = "D:\\project\\workspace\\studyhalle\\src\\main\\java\\s1\\week13\\testRandomAccess.txt";
String mode = "rw";
try {
RandomAccessFile file = new RandomAccessFile(filePath, mode);
for (int i=0; i<tmpArr.length; i++) {
file.writeInt(tmpArr[i]);
}
file.seek(0); // write()하면서 파일포인터가 마지막으로 이동했기때문에 포인터의 위치를 다시 처음으로 이동시킴
// while(true) {
// 아무것도 읽지 못하고 EOFException이 발생하는 것을 방지함
while(file.length() != file.getFilePointer()) {
System.out.println(file.readInt());
}
} catch (Exception e) {
e.printStackTrace();
}
- Java의 정석