728x90

I/O 스트림이란?

I/O 스트림은 Java에서 데이터를 입력(Input)하거나 출력(Output)할 때 사용하는 추상화된 모델입니다.

  • InputStream: 데이터를 읽어오는 데 사용.
  • OutputStream: 데이터를 외부로 쓰는 데 사용.

특징

  • 데이터의 흐름을 Stream으로 간주.
  • Byte 단위 또는 Character 단위로 처리.
  • 데이터 소스: 파일, 네트워크 소켓, 메모리 등.

💡 "Java의 I/O는 Stream 기반이다. 데이터를 한 번에 처리하지 않고, 스트림으로 데이터를 흘려보내면서 효율적으로 작업한다."


InputStream과 OutputStream의 기본 구조

InputStream의 주요 메서드

 
int read() throws IOException  
int read(byte[] b, int off, int len) throws IOException  
void close() throws IOException

OutputStream의 주요 메서드

void write(int b) throws IOException  
void write(byte[] b, int off, int len) throws IOException  
void close() throws IOException
 

주요 I/O 클래스와 사용 사례

파일 읽기: FileInputStream

 
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputExample {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("example.txt")) {
            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) data); // 데이터를 문자로 변환해 출력
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

파일 쓰기: FileOutputStream

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputExample {
    public static void main(String[] args) {
        try (FileOutputStream fos = new FileOutputStream("example.txt")) {
            String data = "Java I/O Stream 예제입니다.";
            fos.write(data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

🔑 TIP: try-with-resources를 사용하면 스트림을 자동으로 닫아 메모리 누수를 방지할 수 있습니다.


Buffered 스트림과 성능 향상

BufferedInputStream 사용 예

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class BufferedInputExample {
    public static void main(String[] args) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("example.txt"))) {
            int data;
            while ((data = bis.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

왜 Buffered 스트림을 사용할까?

  • 기본 스트림은 데이터를 1바이트씩 처리.
  • Buffered 스트림은 버퍼를 사용해 데이터 블록을 한꺼번에 처리 -> 성능 향상.
728x90

+ Recent posts