Java

2024.05.17 Java 유용한 클래스 파일 Copy (바이트기반 입/출력)

정훈5 2024. 5. 17. 09:04

시나리오 코드 1 - 기반 스트림인 파일 입력,출력 스트림을 사용

package io.file.ch03;

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

public class FileCopy {
	
	public static void main(String[] args) {
		
		// 스트림은 기본적으로 단방향 이다. 
		// 입력 스트림, 출력 스트림 두개가 필요 하다. 
		
		// 파일 경로 (복사할 대상) 
		String sourceFilePath = "C:\\Users\\GGG\\Documents\\Lightshot\\a.zip";
		// 목적지 파일 
		String destinationFilePath = "copy1.zip";
		
		// 소요시간 확인 
		long startTime = System.nanoTime();
		
		try (FileInputStream in = new FileInputStream(sourceFilePath);
				FileOutputStream out = new FileOutputStream(destinationFilePath)){
			int data;
			while( (data = in.read() ) != -1  ) {
				// 파일에 출력 
				out.write(data);
			}
			System.out.println("입력스트림--> 출력스트림 --> 입력-->출력 에 반복 완료");
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		long endTime = System.nanoTime();
		long duration = endTime - startTime;
		System.out.println("복사의 소요 시간은 : " + duration);
		
		// 소요 시간을 추 단위로 변환 --> 포맷팅 
		double seconds =  duration / 1_000_000_000.0;
		// String 클래스에 format 메서드 사용해보기 
		String resultFormat = String.format("소요 시간은 : %.6f초 입니다.", seconds);
		// % 는 포맷 지정자의 시작 
		// f 지정자는 float, double 유형의 변수를 인자로 받아 처리 하겠다 
		System.out.println(resultFormat);
		
	}
}

 

package io.file.ch03;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class BufferdFileCopy {

	public static void main(String[] args) {
		// 기반 스트림 + 보조 스트림을 활용해서
		// 파일 복사 기능을 만들고
		// 소요 시간을 측정하시오.

		// ( 바이트 기반 스트림을 활용 )
		// 입력스트림 --> 출력스트림 --> 입력 --> 출력에 반복 완료

		String sourceFilePath = "C:\\Users\\KDP\\a.zip"; // 파일 경로
		String destinationFilePath = "a.zip"; // 목적지 파일 경로

		try (FileInputStream fis = new FileInputStream(sourceFilePath);
				FileOutputStream fos = new FileOutputStream(destinationFilePath);
				BufferedInputStream bis = new BufferedInputStream(fis);
				BufferedOutputStream bos = new BufferedOutputStream(fos);) {
			// 코드 수행 부분
			int data;

			while ((data = bis.read()) != -1) { // 한 바이트 씩 읽어서
				// 파일에 출력
				bos.write(data); // 한 바이트 씩 읽은 데이터를 출력하고
			}
			bos.flush(); // 매번 입출력을 발생 하는 것이 아니라 한번에 입출력을 사용

		} catch (Exception e) {
		}

	} // end of main
} // end of class