InputStream과 OutputStream을 이용하여 콘솔에 간단한 입력과 출력을 해보자


package chap11.exam01.sysio;

import java.io.IOException;
import java.io.InputStream;

public class SysInput {

	public static void main(String[] args) {
		System.out.println("아무거나 입력 하세요!");

		InputStream in = System.in;

		try {
			char a = (char)in.read();
			System.out.println(a);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}



package chap11.exam01.sysio;

import java.io.OutputStream;

public class SysOutput {

	public static void main(String[] args) throws Exception {
		OutputStream os = System.out;
		
		for(byte b = 97; b <= 122; b++) {
			os.write(b); // 바이너리를 내부적으로 처리 (파일 처리용)
//			System.out.println((char)b); // 외부로 출력
		}
		os.flush(); // flush가 없으면 출력이 안 될 수도 있다.
//		os.close(); // 여기서 close를 하면 밑에서 다시 객체화하여도 사용할 수 없음
		
		System.out.println();
		
		
		// 문자열을 배열로 만들어서 출력
		String hangul = "가나다라마바사아자차카타파하";
		
		byte[] aa = hangul.getBytes();
//		for(int i = 0; i < aa.length; i++) {
//			System.out.println((char)aa[i]);
//		}
		os.write(aa);
		// 단일 스레드에서 여러 개의 스트림을 다룰 수 없다.
		os.flush(); // flush가 없으면 출력이 안될 수도 있다.
		os.close();
	}

}


flush는 (변기의)물을 내리다 라는 의미를 가지고 있는데 


Stream을 flush하다 라고 이해하면 쉽다.


현재 메모리에 Stream이 그대로 흘러와 담겨있는데


flush하여 데이터를 뿌려준다고 할 수 있다.


그리고 Stream을 close 한다면 메모리를 반환하게 된다.


close를 한번 한 스트림은 다시 객체화 하여도 사용 할 수 없게 된다.










Console 클래스는 여태껏 사용해온 콘솔창의 입력 받은 문자를 쉽게 읽을 수 있는 클래스이고 cmd(Windows 커맨드 창)에서 실행된다.


Console은 정수, 실수 값을 바로 읽어 들이지 못하기 때문에 Scanner 클래스와 함께 이용하면 쉽게 사용가능하다.


여태껏 사용해온 Scanner scan = new Scanner(System.in);과 같다.




package chap11.exam02.console;

import java.io.Console;

public class Main {

	public static void main(String[] args) {
		// cmd에서만 실행 가능
		// 프로젝트 내 bin 폴더 > java [패키지이름.실행클래스] (경로)
		// 입력 순서 ex
		// d:
		// D:\JAVA\Chapter11\bin
		// java chap11.exam02.console.Main
		
		Console console = System.console();
		
		System.out.print("아이디 : ");
		String id = console.readLine();
		System.out.print("비번 : ");
		char[] pw = console.readPassword();
		String pass = new String(pw);
		System.out.println("---------------------");
		System.out.println("ID : " + id);
		System.out.println("PW : " + pass);
		
	}

}



콘솔 창으로 실행하는 방법은 https://qdgbjsdnb.tistory.com/79?category=715136 에서 확인하자





Scanner은 딱히 설명 할 것이 없으므로 예제만 올려보겠습니다.



package chap11.exam03.scanner;

import java.util.Scanner;

public class ScanMain {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		System.out.print("문자열 입력>");
		String inputStr = scan.nextLine();
		System.out.println(inputStr);
		
		System.out.print("정수 입력>");
		int inputInt = scan.nextInt();
		System.out.println(inputInt);
		
		System.out.print("실수 입력>");
		double inputDouble = scan.nextDouble();
		System.out.println(inputDouble);
		
	}

}




+ Recent posts