[바이트 스트림] 데이터 압축 및 해제 - GZIPOutputStream & GZIPInputStream 사용
Java/Input/Output Facilities 2013. 2. 11. 23:04데이터 압축
package ch12;
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPOutputStream;
public class GZip { public static int sChunk = 8192;
public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GZip source"); return; } // create output stream String zipname = args[0] + ".gz"; GZIPOutputStream zipout; try { FileOutputStream out = new FileOutputStream(zipname); zipout = new GZIPOutputStream(out); } catch (IOException e) { System.out.println("Couldn't create " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; // compress the file try { FileInputStream in = new FileInputStream(args[0]); int length; while ((length = in.read(buffer, 0, sChunk)) != -1) zipout.write(buffer, 0, length); in.close(); } catch (IOException e) { System.out.println("Couldn't compress " + args[0] + "."); } try { zipout.close(); } catch (IOException e) { } } }
|
압축 해제
package ch12; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; public class GUnzip { public static int sChunk = 8192; public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GUnzip source"); return; } // create input stream String zipname, source; if (args[0].endsWith(".gz")) { zipname = args[0]; source = args[0].substring(0, args[0].length() - 3); } else { zipname = args[0] + ".gz"; source = args[0]; } GZIPInputStream zipin; try { FileInputStream in = new FileInputStream(zipname); zipin = new GZIPInputStream(in); } catch (IOException e) { System.out.println("Couldn't open " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; // decompress the file try { FileOutputStream out = new FileOutputStream(source); int length; while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length); out.close(); } catch (IOException e) { System.out.println("Couldn't decompress " + args[0] + "."); } try { zipin.close(); } catch (IOException e) { } } }
'Java > Input/Output Facilities' 카테고리의 다른 글
Filter Stream과 Decorator 패턴 (0) | 2013.11.11 |
---|---|
바이트 Stream과 문자 스트림 (0) | 2013.11.11 |
객체의 직렬화 & serialVersionUID (0) | 2013.02.11 |
[객체 스트림] 객체 Write & 객체 Read (0) | 2013.02.11 |
[문자 스트림] 배열형태로 만든후 내용을 화면으로 출력- CharArrayReader와CharArrayWriter의 사용 (0) | 2013.02.11 |