티스토리 뷰

Java/IO

InputStream, OutputStream

따강아지 2022. 2. 27. 00:19

1. Stream 이란

영어 뚯으로 '흐르는 시냇물'등의 의미로 일반적으로 데이터의 연속적인 흐름을 의미 합니다. 즉 프로그램에서 외부의 데이터를 읽거나 보내기 위한 통로 역활을 합니다.

자바에서 Stream은 java.io Package에 있으면 추상 클래스인 InputStream(외부에서 데이터를 입력), OutputStream(데이터를 외부로 출력)을 상속 받아서 구현한 FileInputStream, FileOutputStream등이 있으며 상속 받아 overriding해서 다양한 역활을 수행 할 있습니다. 자바에서는 Stream은 단반향 입니다

2. InputStream

Byte단위의 자바 입력에 사용되는 최상위 클래스는 입력 스트림 클래스 InputStream을 상속 받아서 구현 한 것으로 파일, 네크워크(소겟), 키보드 등 입력한 테이터를 읽을 때 사용 합니다.


2-1. 주요 API

API 설명
int available() 읽을 데이터(바이트)가 얼마나 남아있는지 반환
abstract int read() 입력 스트림에서 1 바이트 씩 읽고 읽은 바이트를 반환
int read(byte buffer[]) 입력 스트림에서 byte buffer[] 만큼 읽고 읽은 데이터 수를 반환
int read(byte buffer[], int off, int len) 입력 스트림에서 buffer[off] 부터 len개 만큼 buffer에 저장 하고 읽은 데이터의 개수를 반환하고 더 이상 읽을 데이터가 없다면 -1을 반환
 long skip(long n) 읽을 데이터 중 n 바이트를 스킵하고 실제로 스킵한 바이크 개수가 반환
synchronized void mark(int readlimit) 되돌아갈 특정 위치를 마킹하는 메소드
readlimit은 현재 위치를 마킹하고 최대 몇개의 byte를 더 읽을 수 있는지를 의미
synchronized void reset() 마킹한 지점으로 되돌아가는 메소드
기본적으로 지원되지 않으며, InputStream 추상클래스를 상속받은 클래스에서 오버라이딩해주어야 사용가능

void close() InputStream자원 반환

2-2. 파일 읽어 오기

public static void main(String... args) throws IOException {
    File file = readFile("sample.txt");
    InputStream fileStram = inputFileStream(file);
    // 1 byte 씩 읽기
    readChar(fileStram);
    InputStream fileStramBytes = inputFileStream(file);
    // n byte 읽기
    readByte(fileStramBytes, 10);
    fileStram.close();
    fileStramBytes.close();
}

 

  /**
   * 파일 이름을 받아서 파일 객체를 반환 한다.
   * @param fileName
   * @return
   */
  static File readFile(String fileName) {
    String pathname = "d:" + File.separator +
            "works" +  File.separator + "JAVA_EDU"
            + File.separator + "IO"
            + File.separator +  fileName;
    return new File(pathname);
  }

 

  /**
   * 파일 객체를 파일 스트림 객체로 반환 한다.
   * @param file
   * @return
   * @throws IOException
   */
  static InputStream inputFileStream(File file) throws IOException {
    return new FileInputStream(file);
  }

 

  /**
   * 파일 스트림 객체를 읽어서 출력 한다.
   * @param inputStream
   * @param readByteCout      한번에 읽은 바이트 수
   * @throws IOException
   */
  static void readByte(InputStream inputStream, int readByteCout) throws IOException {
    byte[] bytes = new byte[readByteCout];
    int dataCount, totalReadCout = 0;
    while( (dataCount = inputStream.read(bytes)) != -1 ) {
      String str = new String(bytes, 0, dataCount, Charset.forName("UTF-8"));
      System.out.println(str);
      System.out.println("읽은 데이터 :" + dataCount
              + " , 남은 테이터 : " + inputStream.available());
      totalReadCout = totalReadCout + dataCount;
    }
    System.out.println("readByte 총 읽은 데이터 수 : " + totalReadCout);
  }
readByte() 메서드 :  한번에 읽은 Byte의 수를 받아서 읽은 후 문자열로 변환 할 떄 Charset을 UTF-8로 변환
Charset을 UTF-8로 변환하는 이유는 한글 수용 때문이다. 한글은 한 문자가 2Byte로 파일 저장 사 UTF-8로 저장 해야 한다.

 

  static void readChar(InputStream inputStream) throws IOException {
    int dataCount, totalReadCout = 0;;
    while( (dataCount = inputStream.read()) != -1 ) {
      System.out.println("읽은 데이터 :" + (char)dataCount
          + " , 남은 테이터 : " + inputStream.available());
      totalReadCout = totalReadCout + 1;
    }
    System.out.println("readChar 총 읽은 데이터 수 : " + totalReadCout);
  }
readChar() 메서드 :  한번에 1 Byte을 읽어서 사용 

 

3. OutputStream

Byte단위의 자바에서 출력에 사용되는 최상위 클래스로 출력 스트림 클래스는 OutputStream을 상속 받아서 구현 한 것으로 파일, 네크워크(소겟)등  테이터 출력에 사용 합니다.

 

3-1. 주요 API

API 설명
abstract void write(int b) int의 하위 1byte를 output buffer에 출력
void write(byte b[])  메모리 버퍼에 출력
void write(byte b[], int off, int len) off 위치에서 len개을 읽어서 후 출력
void flush() 버퍼에 존재하는 데이터를 목적지까지 보내기( 실제 출력 수행 )
void close() OutputStream자원 반환

3-2. 출력 예제

  static void writeFile() throws IOException {
    File file = getile("newSample.txt");
    if (! file.exists()) file.createNewFile();
    OutputStream outputStream = new FileOutputStream(file, true); // 데이터 연결
    writeStream(outputStream, "신규 파일 생성");
    outputStream.close();
  }

 

  static void writeStream(OutputStream outputStream, String writeStr) throws IOException {
    byte[] bytes =  writeStr.getBytes(StandardCharsets.UTF_8);
    outputStream.write(bytes);
    outputStream.write('\n');
    outputStream.flush();
  }

'Java > IO' 카테고리의 다른 글

File 클래스  (0) 2022.02.26