상세 컨텐츠

본문 제목

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

JAVA

by 미로910 2024. 5. 21. 17:18

본문

문자기반 스트림을 활용한 파일복사 클래스 설계하기
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]; // 한 번 읽을 때 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

실행 결과_________

-------------------------------------------------------------------

▶ 기존의 파일이 copy

 

바이트 기반 스트림을 활용한 Zip 파일 만들어 보기
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) {

		// 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()) >= 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");
	}

}

실행 결과________

--------------------------------------------------

▶ zip 파일이 생성됨

관련글 더보기