Java

2024.05.21 Java 유용한 클래스 파일복사(문자기반 입/출력), ZIP파일로 압축

정훈5 2024. 5. 21. 08:55

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

더보기
package io.file.ch07;

import java.io.FileReader;
import java.io.FileWriter;

public class FileCopyHelper {
	
	// 파일 복사하는 함수
	public static void copyFile(String readFilePath, String writerFilePath) {
		
		// try() -catch - resource
		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("파일 복사 중에 오류 발생");
		} // end of try() -catch - resource
		
	} // end of copyFile()
	
	// 파일 복사 - 버퍼 기능 활용
	
	// 메인 함수
	public static void main(String[] args) {
		
		FileCopyHelper.copyFile("seoul.txt", "copy");
		
	} // end of main

} // end of class

더보기
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() -catch - resource
		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("파일 복사 중에 오류 발생");
		} // end of try() -catch - resource

	} // end of copyFile()

	// 파일 복사 - 버퍼 기능 활용
	public static void copyFileWithBuffer(String readFilePath, String writeFilePath) {
		// try() -catch -resource
		try (
				// 보조 스트림 - 기반스트림
				BufferedReader bufferedReader = new BufferedReader(new FileReader(readFilePath));
				BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(writeFilePath));) {
			// 버퍼를 활용하는 버퍼에 크기를 지정할 수 있다.
			char[] buffer = new char[1024];
			int numCharsRead; // 읽은 문자 수

			while ((numCharsRead = bufferedReader.read(buffer)) != -1) { // 배열의 크기만큼 읽어온다.
				bufferedWriter.write(buffer, 0, numCharsRead);
				System.out.println("numCharRead : " + numCharsRead);
			}
			System.out.println("버퍼를 사용한 파일 복사 완료 : " + writeFilePath);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("버퍼를 사용한 파일 복사 중 오류 발생");
		}

	}

	// 메인 함수
	public static void main(String[] args) {

		FileCopyHelper.copyFile("seoul.txt", "copy");
		System.out.println("--------------------------------");
		FileCopyHelper.copyFileWithBuffer("NewYork.txt", "copyNewYork.txt");

	} // end of main

} // end of class

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

seoul.txt 파일을  zipSeoul.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() - catch - resource
		// ZipOutputStream 을 사용해서 ZIP 형식으로 데이터를 압축할 수 있다.
		// FileOutputStream 을 활용해서 설정
		try(
				// 기반 스트림
				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) {
			// TODO: handle exception
			System.out.println("ZIP 파일 생성 시 오류 발생");
		}
	} // end of zipFile()
	
	// 메인 함수
	public static void main(String[] args) {
		ZipFileHelper.zipFile("seoul.txt", "zipSeoul.zip");
		
	} // end of main

} // end of class