파일복사(문자기반 입/출력), ZIP파일로 압축 - 16

파일복사(문자기반 입/출력), ZIP파일로 압축

💡 학습 목표
    1. 문자기반 스트림을 활용한 파일복사
    2. 바이트 기반 스트림을 활용한 Zip 파일 만들기

1. 문자기반 스트림을 활용한 파일복사

시나리오 코드 1 - 문자기반 스트림을 활용한 파일복사 클래스 설계하기

package io.file.ch07;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

public class FileCopyHelper {

	// 파일 복사
	public static void copyFile(String readFilePath, String writerFilePath) {

		try (FileReader fr = new FileReader(readFilePath); FileWriter fw = new FileWriter(writerFilePath)) {
			int c;
			while ((c = fr.read()) != -1) {
				fw.write(c);
			}
			System.out.println("파일 복사 완료 : " + writerFilePath);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("파일 복사 중 오류 발생");
		}

	}

	// 파일 복사 - 버퍼 활용
	public static void copyFileWithBuffer(String readFilePath, String writerFilePath) {
		try (BufferedReader bufferedReader = new BufferedReader(new FileReader(readFilePath));
				BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(writerFilePath))) {

			// 버퍼를 활용하는 버퍼에 크기를 지정할 수 있다.
			char[] buffer = new char[1024];
			int numCharsRead; // 읽은 문자 수

			while ((numCharsRead = bufferedReader.read(buffer)) != -1) {
				bufferedWriter.write(buffer, 0, numCharsRead);
				System.out.println("numCharsRead : " + numCharsRead);
			}
			System.out.println("버퍼를 사용한 파일 복사 완료" + writerFilePath);

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("버퍼를 사용한 파일 복사중 오류 발생");
		}
	}

	// 메인 함수
	public static void main(String[] args) {
		FileCopyHelper.copyFile("Seoul.txt", "copySeoul.txt");
		System.out.println("------------------------------");
		FileCopyHelper.copyFileWithBuffer("NewYork.txt", "copyNewYork.txt");

	} // end of main

} // end of class

2. 바이트 기반 스트림을 활용한 Zip 파일 만들기

시나리오 코드 2 - 바이트 기반 스트림을 활용한 Zip 파일 만들어 보기

package io.file.ch07;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileHelper {
	
	// 파일을 압축하는 기능 - zip
	public static void zipFile(String fileToZip, String zipFileName) {
		try (
				// ZipOutputStream 을 사용해서 ZIP 형식으로 데이터를 압축할 수 있다.
				// FileOutputStream을 활용해서 설정
				FileInputStream fis = new FileInputStream(fileToZip);
				ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFileName));
				
				){
			// ZipEntry 객체 생성 - 압축 파일 내에서 개별 파일을 나타냅니다.
			ZipEntry zipEntry = new ZipEntry(fileToZip);
			zos.putNextEntry(zipEntry);
			
			// 파일 내용을 읽고 ZIP 파일에 쓰기 위한 버퍼 생성
			byte[] bytes = new byte[1024];
			int length;
			while ((length = fis.read(bytes)) >= 0) {
				zos.write(bytes, 0, length);
			}
			zos.closeEntry();
			System.out.println("ZIP 파일 생성 완료 : " + zipFileName);
			
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("ZIP 파일 생성시 오류 발생");
		}
	}
	
	
	public static void main(String[] args) {
		ZipFileHelper.zipFile("Seoul.txt", "zipSeoul.zip");
	}

}

Java 유용한 클래스 - 3 으로 돌아가기