JAVA

문자 기반 스트림(키보드, 콘솔) 과 보조 기반 스트림(버퍼 스트림)

jiyoon12 2025. 5. 29. 17:05

1. 문자 기반 스트림

  • 문자 기반 + 키보드, 콘솔에 대한 입출력 실습하기
package ch03;

import java.io.*;

/**
 * 바이트 단위 스트림에 이름 형태
 * InputStream(System.in), OutputStream(System.out)
 * 문자 기반 스트림에 이름 형태
 * xxxReader, xxxWriter (문자 기반 형태 네이밍 형식)
 */
public class KeyboardConsoleStream {

    public static void main(String[] args) {
        /**
         * InputStreamReader의 read() 메서드는 하나의 문자를 읽어서
         * 그 문자의 유니코드(UTF-8, UTF-16) 값으로(정수값) 반환 합니다.
         */

        // 프로그램 목표: 키보드에서 문자 기반에 스트림을 사용해서 코드로 데이터를 읽어 보자.
        try (InputStreamReader reader = new InputStreamReader(System.in);
             PrintWriter writer = new PrintWriter(System.out, true)
        ) {
            System.out.println("텍스트를 입력하세요(종료 하려면 ctrl + D)");

//            int charCode = reader.read();
//            System.out.println("-------------------");
//            System.out.println((char)charCode);

            int charCode;
            while ((charCode = reader.read()) != -1) {
                // System.out.println((char)charCode);
                writer.println((char) charCode);
            }
            /**
             * 입력된 문자를 콘솔에 출력을 하는데 버퍼를 즉시 비움
             */
            writer.flush(); // 즉시 출력

        } catch (IOException e) {
            /**
             * 예: 키보드 입력 오류, 콘솔 출력오류가 여기서 catch 됨
             */
            System.out.println("입출력중 오류 발생");
        }
    }
}

 

  • 문자기반 + 파일 입출력 실습하기
package ch03;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileStreamBasic {

    public static void main(String[] args) {
        // 함수 호출
        // writeToFile("basic_output.txt");

        // 함수 호출
        readFromFile("basic_output.txt");

    } // end of main

    // 파일에 텍스트를 쓰는 함수(문자 기반 스트림 사용)
    public static void writeToFile(String fileName) {
        /**
         * FileWriter는 문자 기반 출력 스트림으로, 텍스트를 파일에 기록할 수 있다.
         */

        try (FileWriter writer = new FileWriter(fileName)) {
            // 파일에 기록할 텍스트 선언
            String text = "자바 문자 기반 스트림예제\n";
            writer.write(text); // 파일이 없다면 새로운 파일 생성, 텍스트를 파일에 쓴다
            writer.write("추가 문자열을 기록합니다.");

            // 스트림을 비워 주자. 물을 내리다.
            writer.flush();
            System.out.println("파일에 텍스트를 잘 기록 하였습니다.");

        } catch (IOException e) {
            System.out.println("파일 쓰기 중 오류 발생: " + e.getMessage());
        }
    } // end of writeToFile

    public static void readFromFile(String fileName) {
        /**
         * FileReader는 문자 기반 입력 스트림으로, 파일에서 텍스트를 읽음.
         */
        try (FileReader reader = new FileReader(fileName)) {

            // read() 메서드는 한 문자씩 읽어 유니코드 값(정수)로 반환 한다.
//            int charCode = reader.read();
//            System.out.println(charCode);
//            System.out.println((char) charCode);

            // 파일에 모든 텍스트를 읽을 수 있도록 코딩을 하세요, -1은 파일의 끝을 의미한다.
            int charCode;
            while ((charCode = reader.read()) != -1) {
                System.out.print((char) charCode);
            }


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 

  • 도전 과제
package ch03;

import java.io.*;

/**
 * 문자 기반 스트림을 사용하자.
 * 1. 키보드에서 값을 받아서 파일에 쓰기
 * 2. 다시 그 파일을 읽는 함수를 만들어서 실행하기
 */
public class FileStreamUserInput {

    public static void main(String[] args) {
        // 함수 호출
        // writeUserInputToFile("user_input.txt");

        readFile("user_input.txt");

    } // end of main

    // 키보드에서 입력을 받아 파일에 쓰는 함수를 만들어 보세요
    public static void writeUserInputToFile(String fileName) {
        /**
         * 문자 기반 키보드 입력 스트림 InputStreamReader(System.in) 필요
         * 파일에 텍스트를 쓰는 스트림
         * try-with-resource 로 자원 자동 닫기 처리
         */

        try (InputStreamReader reader = new InputStreamReader(System.in);
             // 두번째 인자값 true -> append 모드 활성화
             FileWriter writer = new FileWriter(fileName, true)) {

            System.out.println("콘솔에서 텍스트를 입력");
            // 한 문자씩 읽고 유니코드 정수값 반환 reader.read()
            int charCode;
            while ((charCode = reader.read()) != -1) {
                writer.write(charCode);
                writer.flush(); // 문자 하나 받고 물 내리기
            }
            System.out.println(fileName + ".txt 파일에 텍스트를 모두 씀.");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    // 파일에서 텍스트를 읽는 함수 만들어 보기 - 문자 기반
    public static void readFile(String fileName) {
        /**
         * 문자 기반 입력 스트림
         * 콘솔창에 출력 System.out.println(); 사용
         */
        try (FileReader reader = new FileReader(fileName)) {
            // 한 문자 씩 읽어오기
//            int charCode = reader.read();
//            System.out.println(charCode);
//            System.out.println((char) charCode);
//
            int charCode;
            while ((charCode = reader.read()) != -1) {
                System.out.print((char) charCode);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 


2. 보조 기반 스트림

  • 바이트 기반 스트림 + 보조 스트림(버퍼 스트림) 활용
package ch04;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

/**
 * 보조 기반 스트림에 대해서 알아보자.
 * 기반 스트림이 있어야 사용할 수 있다.
 * (InputStream, InputStreamReader, OutputStream, OutputStreamWriter)
 */
public class ByteBufferedKeyboardConsole {

    public static void main(String[] args) {
        // 바이트 기반 스트림 + 버퍼드 스트림
        // System.in.read()
//        BufferedInputStream bis = new BufferedInputStream(System.in);
//        BufferedOutputStream bos = new BufferedOutputStream(System.out);

        try(BufferedInputStream bis = new BufferedInputStream(System.in);
            BufferedOutputStream bos = new BufferedOutputStream(System.out);) {

            /**
             * 보조 스트림을 활용해서 한번에 1024바이트 크기의 버퍼 배열로
             * 데이터를 읽자
             */
            // 버퍼 도구 준비
            byte[] buffer = new byte[1024];
            int byteRead;

            // bis.read(); // 1 바이트 씩 읽음
            // bis.read(buffer); // 1024 바이트 씩 읽음

            while((byteRead = bis.read(buffer)) != -1){
                // System.out.println() 와 같음
                bos.write(buffer, 0, byteRead);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}