컴퓨터공학 💻 도서관📚

Part2. 6-13 표준 입출력 스트림 본문

✅🌲강의 복습 노트/패캠 JavaSpring 강의,코드 복습

Part2. 6-13 표준 입출력 스트림

들판속초록풀 2025. 8. 22. 16:47

System 클래스의 표준 입출력 멤버

public class System{    // System이라는 클래스가 있다.
	public static PrintStream out;    // static 변수로 선언되어 있다. 그래서 우리가 new하지 않고 썼던 것이다.
	public static InputStream in; 
	public static PrintStream err; 
}
  • System.out
    표준 출력(모니터) 스트림
    System.out.println("출력 메세지");
  • System.in
    표준 입력(키보드) 스트림
    int d = System.in.read()   // 한 바이트 읽기 ,  read의 반환값은 int 이다.
  • System.err
    표준 에러 출력(모니터) 스트림
    System.err.println("에러 메세지");

System.in 사용하기 예제

import java.io.IOException;

public class SystemInTest1 {

	public static void main(String[] args) {
		System.out.println("알파벳 하나를 쓰고 [Enter]를 누르세요");
		
		int i;
		try {
			i = System.in.read();    // 오류가 발생할 수 있으니 예외처리 해줘야 한다.
			System.out.println(i);
			System.out.println((char)i);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
import java.io.IOException;

public class SystemInTest2 {

	public static void main(String[] args) {
		System.out.println("알파벳 여러 개를 쓰고 [Enter]를 누르세요");
		
		int i;
		try {
			while( (i = System.in.read()) != '\n' ) {  // 한 바이트씩 읽기 때문에 한글 쓰면 깨진다. 문자는 2바이트 이상이다.
				System.out.print((char)i);           // 그래서 보조 스트림으로 감싸야지 한글이 처리가 된다.
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
import java.io.IOException;
import java.io.InputStreamReader;  // 보조스트림 사용을 위해 import

public class SystemInTest2 {

	public static void main(String[] args) {
		System.out.println("알파벳 여러 개를 쓰고 [Enter]를 누르세요");
		
		int i;
		try {
                        InputStreamReader irs = new InputStreamReader(System.in);  // 보조 스트림 사용
			while( (i = irs.read()) != '\n' ) {    // irs 변수 사용
				System.out.print((char)i);          
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

위 코드에서 보조 스트림이 지금은 표준 입력 스트림을 감쌌지만,  파일 input stream을 감싸면 파일에서 한글을 읽을 수 있게 된다.

 

 

 

 

Comments