본문 바로가기
Java/자바 Stream

[Java] 81. 파일 출력 스트림 (바이트)

글: Song hyun 2024. 5. 16.
728x90
반응형

[Java] 80. 파일 출력 스트림 (바이트)

1. 버퍼란?

2. 버퍼의 기본 원리

3. 버퍼 사용의 단점


 

1. 버퍼란?

 

2. 버퍼의 기본 원리

(1) 효율성 증가

(2) 시스템 부하 감소

(3) 데이터 전송 속도 개선

 

3. 버퍼 사용의 단점

 

package io.ch02;

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

public class MyFileOutputStream {

	// 코드의 시작점
	public static void main(String[] args) {
		
		long start=System.nanoTime();
		
		// 데이터가 존재
		String data = "Hello, Java FileOutputStream \n 안녕 반가워";
		
		// 1. 파일에 데이터를 저장하고 싶다면(바이트 기반)
		// 자바 8버전부터 제공
		// try-catch-resource -> 자동으로 자원을 닫아준다.
		
		try(
				FileOutputStream fos = new FileOutputStream("output.txt", false)
		) { 
			// data(string) 가지고 있는 문자열들을 바이트 배열로 반환 처리
			
			byte[] bytes = {72,101,108,108, 111}; //hello
			
			//byte[] bytes = data.getBytes();
			System.out.println("byte : "+bytes);
			for(int i=0; i<bytes.length; i++) {
				System.out.println("bytes[i] : "+bytes[i]);
			}
			
			//  연결된 스트림을 활용해 바이트 배열을 파일에 흘려 보냄
			fos.write(bytes);
			System.out.println("파일출력 스트림을 통해서 데이터를 씀");
			
		} catch (FileNotFoundException e) {
			System.out.println("파일이 없음");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		// 동작 이해해 보기
		// 파일에 바이트 단위로 데이터를 쓰고
		// 그 파일을 열었을 때, 글자로 보이는 이유는 
		// 파일을 읽는 프로그램이 파일 내에 바이트 데이터를
		// 문자로 해석해서 보여주었다. (문자 인코딩)
		long end=System.nanoTime();
		long duration =  end-start;
		System.out.println("스트림 기반 파일 입출력 소요 시간 : "+duration);
	}

}
package io.ch02;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

public class MyByfferedOutputStream {
	
	public static void main(String[] args) {
		long start = System.nanoTime();
		String data = "기반 스트림 + 보조 스트림을 활용해보자";
		
		// 현재 시간(측정)
		
		// try-catch-resource 활용
		try (
				FileOutputStream fos = new FileOutputStream("output2.txt");
				BufferedOutputStream bos = new BufferedOutputStream(fos);
				){
			// 코드 수행 부분
			byte[] bytes = data.getBytes();
			
			// 보조 스트림 (버퍼)
			bos.write(bytes);
			
			// 버퍼에 데이터가 남아 있다면 중복된 데이터를 쓸 수 있다.
			// 한 번 사용한 다음에
			bos.flush(); // flush -> 물을 내리다
			
			System.out.println("보조 스트림을 활용한 파일 출력 완료");
			// 실행에 걸리는 시간을 측정해보고 싶다!
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// 현재 시간(종료)
		long end = System.nanoTime();
		// 종료 - 시작 = 소요 시간
		long duration = end - start;
		System.out.println("소요 시간 : "+duration);
		// 나노초는 10억분의 1
		
	}
	
}
728x90
반응형