본문 바로가기
Programming/Java * Spring

[Java] 14. Buffered Input/Output Stream, 일반 Stream과 속도 비교

by 고막고막 2019. 4. 5.

파일 입출력(I/O)

자바에서 데이터 입출력은 Stream을 통해 이루어진다. 프로그램을 기준으로 들어오면 Input(읽기), 내보내면 Output(쓰기)로 방향을 결정하고, 데이터의 교환을 위해서는 Input과 Output을 모두 만들어야 한다. 입출력과 관련된 모든 작업은 java.io 패키지에서 제공하고 있다.

Input/Output Stream

바이트 기반 입출력 클래스의 최상위 클래스이자 추상클래스이다. 입출력할 데이터가 OS와 JVM을 거쳐 메모리에 1byte씩 전달된다. 이는 마치 쇼핑몰에서 주문한 상품이 모든 지역의 구매자에게 하나하나씩 전달되는 것과 같다.

Buffered Input/Output Stream

필터 클래스 중에 버퍼(Queue 구조로 되어있는 임시 저장소)를 제공하는 클래스. App안에 default 2MB 짜리 버퍼를 생성해서 버퍼가 File을 한번에 받아준 후 1byte씩 메모리에 전달된다. 쇼핑몰에서 주문한 상품들이 지역 담당의 택배기사(버퍼)에게 전달되어 택배기사가 그 지역 안의 구매자들에게 전달해주는 것과 같다. 이동 경로가 단축되어 시간 cost가 현저히 줄어든다.

Input/Output Stream vs. Buffered Input/Output Stream 속도 비교

public static void main(String[] args) throws IOException {
	InputStream in = new FileInputStream("putty.exe");
	OutputStream out = new FileOutputStream("퓨푸티.exe");
	int copyByte = 0;
	int data;
	long stime = System.currentTimeMillis();
	while(true) {
		data = in.read();	// 1byte씩 읽는다
		if(data==-1)		// 더 이상 읽을 것이 없다
			break;
		out.write(data);
		copyByte++;
	}
long etime = System.currentTimeMillis();
in.close();
out.close();
System.out.println("복사 시간: "+(etime-stime));
System.out.println("복사된 배열의 크기: "+copyByte);
}

public static void main(String[] args) throws IOException {
	InputStream in = new FileInputStream("putty.exe");
	OutputStream out = new FileOutputStream("푸티.exe");
	BufferedInputStream bin = new BufferedInputStream(in);
	BufferedOutputStream bout = new BufferedOutputStream(out);

	int copyByte = 0;
	int bData;
	long stime = System.currentTimeMillis();
	while(true) {
		bData = bin.read();
		if(bData == -1)
		break;
	bout.write(bData);
	copyByte++;
	}
	long etime = System.currentTimeMillis();		
	bin.close();
	bout.close();
	System.out.println("---------------버퍼 스트림 전송시간--------------------");
	System.out.println("복사 시간: "+(etime-stime));
	System.out.println("복사된 바이트의 크기: "+copyByte);
}