JAVA

[Java] 입출력 스트림 I/O Stream

vluevy 2021. 8. 24. 20:26
728x90
반응형

입출력스트림 I/O Stream

  • 자바의 입출력은 스트림에 의해 이루어짐
  • 스트림이란 응용프로그램과 입출력 장치를 연결하는 소프트웨어 모듈로 데이터가 순서대로 전송되도록 함
  • 바이트 스트림(Byte Stream) : 1byte 단위, 기본 입출력 단위
  • 문자 스트림(Character Stream) : 2byte 단위

Byte Stream

InputStream

  • read()
  • skip()

OutputStream

  • write(바이트배열)
  • write(b[], off, len)
  • write(data)
  • flush()

Character Stream

Reader

  • BufferedReader
  • InputStreamReader
  • FileReader

Writer

  • BufferedWriter
  • OutputStreamWriter
  • PrintWriter
  • FileWriter

파일 복사하는 코드 예시

GOOD

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileCopyEx {
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String source, dest;

        FileOutputStream fos = null;
        FileInputStream fis = null;

        byte[] b = new byte[2048];
        int len;

        try {
            System.out.println("파일 복사...");

            System.out.println("복사할 원본 파일명 ? ");
            source = br.readLine();

            System.out.println("복사시킬 대상 파일명 ? ");
            dest = br.readLine();

            fis = new FileInputStream(source);
            fos = new FileOutputStream(dest);

            long s = System.currentTimeMillis();
            // len=fis.read(b) => 최대 바이트 배열 b길이 만큼 읽어 b에 저장하고 실제로 읽어들인 byte수를 반환
            while ((len = fis.read(b)) != -1) {
                fos.write(b, 0, len);
            }
            fos.flush();
            long e = System.currentTimeMillis();

                System.out.println("파일 복사 완료: " + (e - s) + "ms");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e2) {
                }
            }

            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e2) {
                }
            }
        }
    }
}

BAD

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileCopyEx {
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String source, dest;

        FileOutputStream fos = null;
        FileInputStream fis = null;

        try {
            System.out.println("복사할 원본 파일명 ? ");
            source = br.readLine();

            System.out.println("복사시킬 대상 파일명 ? ");
            dest = br.readLine();

            fis = new FileInputStream(source);
            fos = new FileOutputStream(dest);

            // 잘못된 코딩의 예 - 시간이 엄청나게 소모됨
            int data;
            long s = System.currentTimeMillis();
            while((data = fis.read())!=-1) {
                fos.write(data);
            }
            fos.flush();
            long e = System.currentTimeMillis();

            System.out.println("파일 복사 완료..."+ (e - s) + "ms");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (Exception e2) {
                }
            }

            if(fos != null) {
                try {
                    fos.close();
                } catch (Exception e2) {
                }
            }
        }
    }
}
반응형