Java I / O 학습 노트 (8) 파일 압축

2210 단어
package files;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class TestZipStream {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		testZipCompress("input.txt", "output.txt");
		testZipUncompress();
	}

	public static void testZipCompress(String... fileNames) throws IOException {
		FileOutputStream fos = new FileOutputStream("test.zip");
		CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32());
		ZipOutputStream zos = new ZipOutputStream(cos);
		BufferedOutputStream bos = new BufferedOutputStream(zos);
		zos.setComment(new String("    ".getBytes("UTF-16BE")).intern());

		BufferedInputStream br = null;
		for (int i = 0; i < fileNames.length; i++) {
			br = new BufferedInputStream(new FileInputStream(fileNames[i]));
			zos.putNextEntry(new ZipEntry(fileNames[i]));
			int c = 0;
			while ((c = br.read()) != -1) {
				bos.write(c);
			}
			br.close();
			bos.flush();
		}

		System.out.println("Compress CRC32: " + cos.getChecksum().getValue());

		bos.close();
	}

	public static void testZipUncompress() throws IOException {
		FileInputStream fis = new FileInputStream("test.zip");
		CheckedInputStream cis = new CheckedInputStream(fis, new CRC32());
		ZipInputStream zis = new ZipInputStream(cis);
		BufferedInputStream bis = new BufferedInputStream(zis);

		BufferedOutputStream bos = null;
		ZipEntry ze = null;
		while ((ze = zis.getNextEntry()) != null) {
			System.out.println(ze);
			bos = new BufferedOutputStream(new FileOutputStream(ze.toString()
					+ ".txt"));
			int x = 0;
			while ((x = bis.read()) != -1) {
				bos.write(x);
			}
			bos.close();
		}

		System.out.println("Uncompress CRC32: " + cis.getChecksum().getValue());

		bis.close();
	}
}

좋은 웹페이지 즐겨찾기