Computer >> Máy Tính >  >> Lập trình >> Java

Làm thế nào để nén một tệp trong Java?

Lớp DeflaterOutputStream của Java được sử dụng để nén dữ liệu đã cho và truyền dữ liệu đó đến đích.

Phương thức write () của lớp này chấp nhận dữ liệu (ở định dạng số nguyên và byte), nén nó và ghi nó vào đích của đối tượng DeflaterOutputStream hiện tại. Để nén tệp bằng phương pháp này &Minus;

  • Tạo FileInputStream đối tượng, bằng cách chuyển đường dẫn của tệp được nén ở định dạng Chuỗi, làm tham số cho phương thức khởi tạo của nó.
  • Tạo FileOutputStream đối tượng, bằng cách chuyển đường dẫn của tệp đầu ra, ở định dạng Chuỗi, làm tham số cho phương thức khởi tạo của nó.
  • Tạo DeflaterOutputStream bằng cách chuyển FileOutputStream đã tạo ở trên đối tượng, như một tham số cho phương thức khởi tạo của nó.
  • Sau đó, đọc nội dung của tệp đầu vào và ghi bằng phương thức write () của lớp DeflaterOutputStream.

Ví dụ

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.DeflaterOutputStream;
public class CompressingFiles {
   public static void main(String args[]) throws IOException {
      //Instantiating the FileInputStream
      String inputPath = "D:\\ExampleDirectory\\logo.jpg";
      FileInputStream inputStream = new FileInputStream(inputPath);
      //Instantiating the FileOutputStream
      String outputPath = "D:\\ExampleDirectory\\compressedLogo.txt";
      FileOutputStream outputStream = new FileOutputStream(outputPath);
      //Instantiating the DeflaterOutputStream
      DeflaterOutputStream compresser = new DeflaterOutputStream(outputStream);
      int contents;
      while ((contents=inputStream.read())!=-1){
         compresser.write(contents);
      }
      compresser.close();
      System.out.println("File compressed.......");
   }
}

Đầu ra

File compressed.......