PrintStream
- System.out은 PrintStream의 객체이다.
- 다른 출력 스트림의 기능을 추가하여 다양한 데이터 값의 표현을 편리하게 출력한다.
- 다른 출력 스트림과는 다르게 IOException이 발생하지 않는다.
- 자동으로 flush()가 되도록 생성할 수 있다. 자동으로 플래시 되는 경우, println() 메소드나 개행 문자, 또는 byte(\n)에 의해 자동으로 flush() 메소드가 호출된다.
- 인코딩을 설정하지 않으면 디폴트 문자 인코딩을 사용해 바이트로 변환한다.
- OutputStream, FilterOutputStream 클래스의 하위 클래스이다.
public class Ex07_PrintStream_write {
public static void main(String[] args) {
// System.out : PrintStream 객체
// PrintStream : 다양한 출력이 가능한 출력 스트림(필터 스트림)
// IOException이 발생되지 않음.
System.out.write(65); // 하위 1byte를 출력 버퍼로 보냄
System.out.write(65);
System.out.write(65);
System.out.flush(); // 출력 버퍼의 내용을 출력 장치로 보냄
}
}
InputStream과 OutputStream은 checked Exception이 존재하기 때문에 try ~ catch 를 사용해야 에러가 뜨지 않았지만, PrintStream은 try ~ catch 없이 사용이 가능하다.
import java.io.PrintStream;
/*
- PrintStream 클래스
System.out은 PrintStream 객체
다른 출력 스트림의 기능을 추가하여 다양한 데이터 값의 표현을 편리하게 출력
IOException 발생하지 않는다.
자동으로 flush()가 되도록 생성할 수 있다.
*/
public class Ex010_PrintStream {
public static void main(String[] args) {
String name = "홍길동";
int kor = 80;
int eng = 90;
int mat = 100;
// String => byte[]
// byte[] b = name.getBytes();
try (PrintStream ps = new PrintStream("test.txt")) {
// ps.println(name+"\t"+kor+"\t"+eng+"\t"+mat);
// ps.printf("%10s %5d %5d %5d", name, kor, eng, mat);
ps.print("이름:"+name+",");
ps.print(kor+",");
ps.print(eng+",");
ps.print(mat);
System.out.println("파일 저장 완료");
} catch (Exception e) {
e.printStackTrace();
}
}
}
문자와 숫자가 모두 섞여 있지만 (String, int) PrintStream을 통해서 편리하게 출력할 수 있다.
test.txt 에 출력하라는 의미. 실행 후
test.txt 파일이 만들어지고 그 안에 출력되었음을 알 수 있다.
PrintWriter 클래스
- PrintWriter 클래스는 포맷된 오브젝트의 표현을 텍스트 출력 스트림에 출력한다.
- PrintStream에 있는 print메소드가 모두 구현되어 있다. 단, 인코딩 되지 않은 바이트 스트림을 사용해야하는 메소드는 포함되어 있지 않다.
- 일부분의 생성자를 제외하고는 예외를 throws 하지 않는다.
- PrintStream 클래스와 다르게 자동 플러시(autoFlush) 활성화된 경우 개행 문자를 출력할 때가 아닌, println(), printf(), format() 메소드가 호출될 때만 자동 플러시된다. print() 메소드 등은 flush() 가 호출되거나 PrintWriter객체가 close()될 때 수행된다.
- Writer 클래스의 하위 클래스이다.
import java.io.PrintWriter;
// PrintWriter : 바이트가 아닌 문자를 출력할 때 사용
public class Ex013_PrintWriter {
public static void main(String[] args) {
// PrintStream -> PrintWriter
/*
PrintWriter pw = new PrintWriter(System.out);
pw.print("자바");
pw.print("오라클");
pw.println("web");
pw.flush(); // flush()를 호출하거나 close()해야 출력
*/
// true 옵션을 주면 flush()를 호출하거나 println()을 호출하면 출력
PrintWriter pw = new PrintWriter(System.out, true);
pw.print("자바");
pw.print("오라클");
pw.println("web");
}
}
'쌍용강북교육센터 > 8월' 카테고리의 다른 글
0823_Java : Writer 클래스 (0) | 2021.08.24 |
---|---|
0823_Java : Reader 클래스 (0) | 2021.08.23 |
0823_Java : OutputStream 클래스 (0) | 2021.08.23 |
0823_Java : InputStream 클래스 (0) | 2021.08.23 |
0820_Oracle[PL/SQL] : 예외처리 (0) | 2021.08.23 |