Java PrintStream 클래스 마스터하기: print, println, printf 완전 정복
Java PrintStream 클래스 마스터하기
이 튜토리얼은 Java의 PrintStream 클래스를 다루며, 생성, 핵심 메서드, 실전 예제를 다룹니다.
java.io 패키지의 PrintStream 클래스는 OutputStream을 확장하며 원시 바이트가 아닌 사람이 읽을 수 있는 텍스트 출력을 위해 설계되었습니다.
PrintStream 작동 원리
다른 스트림과 달리 PrintStream은 기본 타입 값(int, char 등)을 쓰기 전에 포맷된 텍스트로 변환합니다. 또한 IOException을 절대 던지지 않으며, 대신 checkError()로 오류를 보고합니다.
자동 플러시는 핵심 기능으로, 다음 경우 스트림이 자동으로 플러시됩니다:
- 개행 문자(
\n)가 출력될 때,
println() 메서드가 호출될 때, 또는
- 바이트 배열이 쓰여질 때.
PrintStream 생성하기
먼저 클래스를 임포트합니다:
import java.io.PrintStream;
1. 기존 OutputStream에서
// 예: FileOutputStream 래핑
FileOutputStream fos = new FileOutputStream("log.txt");
PrintStream ps = new PrintStream(fos, true); // true = autoFlush
선택적 자동 플러시와 함께 log.txt에 포맷된 텍스트를 씁니다.
2. 파일명에서 직접
PrintStream ps = new PrintStream("log.txt", true);
생성자는 자동 플러시용 불리언을 받습니다. 기본적으로 플랫폼의 문자 인코딩을 사용합니다.
3. 캐릭터셋 지정
PrintStream ps = new PrintStream("log.txt", true, StandardCharsets.UTF_8);
Charset을 사용하여 UTF-8, UTF-16 또는 지원되는 인코딩을 선택할 수 있습니다.
참고: 캐릭터셋에 대한 자세한 내용은 Java Charset API를 참조하세요.
PrintStream의 핵심 메서드
print()와 println()
print(Object obj) - 객체의 문자열 표현을 출력합니다.
println(Object obj) - 플랫폼별 줄 종료자를 추가합니다.
예제: System.out 사용
public class Main {
public static void main(String[] args) {
System.out.print("Hello World.");
}
}
여기서 System.out은 사전 구성된 PrintStream이므로 print() 메서드를 즉시 사용할 수 있습니다.
예제: 파일에 쓰기
import java.io.PrintStream;
public class Main {
public static void main(String[] args) {
try {
PrintStream ps = new PrintStream("output.txt");
ps.print("This is a text inside the file.");
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
결과 output.txt에는 다음이 들어있습니다:
This is a text inside the file.
printf()
포맷 지정자를 사용하여 포맷된 텍스트를 출력합니다:
System.out.printf("I am %d years old", 25);
여기서 %d는 정수 값 25로 대체됩니다.
예제: 파일과 함께 printf() 사용
import java.io.PrintStream;
public class Main {
public static void main(String[] args) {
try {
PrintStream ps = new PrintStream("output.txt");
int age = 25;
ps.printf("I am %d years old.", age);
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
실행 후 output.txt에는 다음이 들어있습니다:
I am 25 years old.
추가 PrintStream 메서드
| 메서드 | 설명 |
close() | 스트림을 닫고 시스템 자원을 해제합니다. |
checkError() | 스트림이 오류를 겪었으면 true를 반환합니다. |
append() | 지정된 문자 시퀀스를 스트림에 추가합니다. |
포괄적인 세부 사항은 공식 Java PrintStream 문서를 참조하세요.