Java by API/java.util.zip/GZIPOutputStream — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 14:22, 31 мая 2010

GZIPOutputStream: write(byte[] buf, int off, int len)

 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.GZIPOutputStream;
public class Main {
  public static void main(String[] args) throws Exception {
    int sChunk = 8192;
    String zipname = "a.gz";
    FileOutputStream out = new FileOutputStream(zipname);
    GZIPOutputStream zipout = new GZIPOutputStream(out);
    byte[] buffer = new byte[sChunk];
    FileInputStream in = new FileInputStream(args[0]);
    int length;
    while ((length = in.read(buffer, 0, sChunk)) != -1)
      zipout.write(buffer, 0, length);
    in.close();
    zipout.close();
  }
}





new GZIPOutputStream(OutputStream out)

 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class MainClass {
  public static void main(String[] args) {
    int bufferSize = 8192;
    // create output stream
    String sourceFileName = "data.txt";
    String zipname = sourceFileName + ".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[bufferSize];
    // compress the file
    try {
      FileInputStream in = new FileInputStream(sourceFileName);
      int length;
      while ((length = in.read(buffer, 0, bufferSize)) != -1)
        zipout.write(buffer, 0, length);
      in.close();
    } catch (IOException e) {
      System.out.println("Couldn"t compress " + sourceFileName + ".");
    }
    try {
      zipout.close();
    } catch (IOException e) {
    }
  }
}