I/O Stream (입출력 스트림)

제민·2024년 7월 26일

Java 개념 공부

목록 보기
18/21
post-thumbnail

스트림의 개념

프로그램 상의 데이터를 외부 매체로 출력하거나 외부 매체로부터 입력을 받아올 때, 반드시 외부 매체와 연결되는 통로가 필요합니다.
이 통로를 '스트림'이라고 합니다.

스트림의 특징

  • 단방향: 입력 스트림과 출력 스트림이 구분되며, 입력과 출력을 동시에 수행하려면 각각 별도의 스트림이 필요합니다.
  • 선입선출(FIFO): 먼저 보낸 데이터가 먼저 도착합니다.
  • 시간 지연: 데이터 전송 시 시간이 지연될 수 있습니다.

스트림의 구분

  1. 바이트 스트림: 1바이트 단위로 데이터 전송 (InputStream, OutputStream)
  2. 문자 스트림: 2바이트 단위로 데이터 전송 (Reader, Writer)

파일 생성 예제

package l.io.ex1;

import java.io.File;
import java.io.IOException;

public class Run {

    public static void main(String[] args) {
        // 1. 경로지정을 딱히 하지 않고 파일 생성하기
        File f1 = new File("test.txt"); // 파일 객체 생성 (실제 파일 X)
        // 2. 존재하는 폴더에 파일 생성
        File f2 = new File("D:\\test2.txt");
       
        try {
            f1.createNewFile(); // 파일 생성
            f2.createNewFile();
           
            // 3. 폴더를 먼저 만들고 파일 생성
            File tmpFolder = new File("D:\\tmp");
            tmpFolder.mkdir();
           
            File f3 = new File("D:\\tmp\\test3.txt");
            f3.createNewFile();
           
            System.out.println(f1.exists());
            System.out.println(f1.isFile());

            // 파일 정보 출력
            File folder = new File("parent");
            folder.mkdir();
            File file = new File("parent\\person.txt");
            file.createNewFile();
            System.out.println("파일명 : " + file.getName());
            System.out.println("파일경로 : " + file.getAbsolutePath());
            System.out.println("파일용량 : " + file.length());
            System.out.println("파일상위폴더 : " + file.getParent());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

스트림 예제

파일 입출력 (File Input/Output)

package l.io.ex3;

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

public class FileByte {

    // 파일에 데이터 출력
    public void fileSave() {
        try (FileOutputStream fout = new FileOutputStream("byte_test.txt", true)) {
            fout.write('a');
            fout.write('9');
            byte[] array = {102, 103, 104};
            fout.write(array);
            fout.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 파일로부터 데이터 읽기
    public void fileRead() {
        try (FileInputStream fin = new FileInputStream("byte_test.txt")) {
            int value;
            while ((value = fin.read()) != -1) {
                System.out.print((char) value);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

문자 기반 스트림

package l.io.ex3;

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

public class FileChar {

    public void fileSave() {
        try (FileWriter fw = new FileWriter("char_test.txt")) {
            fw.write("IO가 너무너무 재미있다.");
            fw.write(" ");
            fw.write("\n");
            fw.write("안녕 ");
            char[] arr = {'저', '는', ' ', '전', '제', '민', '입', '니', '다'};
            fw.write(arr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void fileRead() {
        try (FileReader fr = new FileReader("char_test.txt")) {
            int value;
            while ((value = fr.read()) != -1) {
                System.out.print((char) value);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

객체 저장 및 읽기

package l.io.ex2;

import java.io.Serializable;

public class Product implements Serializable {
    private String name;
    private int price;
   
    public Product(String name, int price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Product [name=" + name + ", price=" + price + "]";
    }
}
package l.io.ex2;

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;

public class ServeStream {

    // 객체를 파일에 저장
    public void objectSave() {
        Product ph1 = new Product("아이폰1", 1000000);
        Product ph2 = new Product("아이폰2", 2000000);
        Product ph3 = new Product("아이폰3", 3000000);
       
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("product1.txt"))) {
            oos.writeObject(ph1);
            oos.writeObject(ph2);
            oos.writeObject(ph3);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 파일에서 객체 읽기
    public void objectRead() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("product1.txt"))) {
            while (true) {
                System.out.println(ois.readObject());
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
profile
초보부터 시작하는 개발자 생활

0개의 댓글