Java

java) java IO - 파일 입력스트림 & 출력스트림 예제

조충희 2025. 5. 28. 19:20

자바 IO, 스트림의 개념

https://notion6780.tistory.com/94

 

java) java 입출력 I/O, 키보드 입력스트림

⭐자바 입출력 I/Oinput/output데이터를 읽고 쓰는 기능을 제공한다파일, 네트워크, 콘솔 등 다양한 소스와 대상 간 데이터를 주고받는다. 먼저 I/O 시스템은 크게 네 가지 주요 구성 요소로 나눈다

notion6780.tistory.com

개념설명에 이어 예제를 통해 배워봤다.

 

 

예제)

txt 파일로부터 입력스트림을 받아봤다.

public class MyFileInputStream {
    public static void main(String[] args) {

        //파일을 바이트 단위로 읽어들이는 방법
        FileInputStream in = null;
        int readData;
        try {
            in = new FileInputStream("a.txt");

            readData = in.read();
            System.out.println("readData:" + readData);
            System.out.println("readData:" + (char)readData);

            readData = in.read();
            System.out.println("readData:" + readData);
            System.out.println("readData:" + (char)readData);

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }//main
}//class

 

예제2)

/* a.txt 파일로부터
        바이트 단위로 데이터를 읽어
        콘솔창에 출력해보자
        주의점
        한글은 3바이트 기반이라
        1바이트씩 읽으면 깨짐 현상이 발생할 수 있다. */
try (FileInputStream in = new FileInputStream("a.txt")) {

            /* 사전 기반 지식
            파일에서 바이트 단위로 데이터를 읽을 때
            더 이상 읽을 데이터가 없으면
            정수값 -1을 반환한다. */

            int readData;
            while ((readData=in.read()) != -1) {
                System.out.print((char)readData);
            }

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

 

예제3)

파일 출력스트림.. 데이터를 내보내보자

String data = "Hello, Java FileOutputSystem 안녕 반가워";

        /* new FileOutputStream 은 파일이 없으면 새로 생성해서 데이터를 입력한다
        Append 모드 활성화 처리 (2번째 인자값 true) */
        try (FileOutputStream fos = new FileOutputStream("output.txt", true)) {
            //문자열 data의 값을 byte 배열로 변환한다
            byte[] dataBytes = data.getBytes();

            //[72, 101, 108..]

            // byte 단위로 파일에 데이터를 입력한다
            fos.write(dataBytes);

            System.out.println("파일 출력 완료: output.txt");
           
            /* output.txt 파일을 열때
            텍스트로 보이는 이유는
            에디터가 바이트 데이터를
            문자열로 해석해서 보여줬기 때문이다. */

        } catch (Exception e) {
            throw new RuntimeException(e);
        }//try-catch

output.txt 라는 새로운 파일이 생성됐다

예제4)

파일로부터 데이터를 받아와 수정한 뒤 새로운 파일을 생성해보자

        int readData;
        String data = "in a galaxy far far away\n";
        byte[] dataBytes = data.getBytes();

        try(FileInputStream fis = new FileInputStream("my1.txt");
            FileOutputStream fos = new FileOutputStream("my2.txt", true)) {

            while((readData = fis.read()) != -1 ) {
                fos.write(readData);
            }
            fos.write(dataBytes);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }//try-catch