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

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

Java cung cấp một lớp có tên là InflaterInputStream lớp này được sử dụng để giải nén một tệp nén.

Phương thức read () của lớp này đọc một byte dữ liệu nén từ luồng đầu vào. Để giải nén tệp nén bằng phương pháp này -

  • Tạo FileInputStream , bỏ qua đường dẫn của tệp nén ở định dạng Chuỗi, làm tham số cho hàm tạo của nó.
  • Tạo FileOutputStream , bỏ qua đường dẫn của tệp đầu ra (tệp hình ảnh không nén), ở định dạng Chuỗi, làm tham số cho hàm tạo của nó.
  • Tạo InflaterInputStream , bỏ qua 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 InflaterInputStream và ghi bằng phương thức write () của lớp FileOutputStream.

Ví dụ

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.InflaterInputStream;
public class DeCompressingFiles {
   public static void main(String args[]) throws IOException {
      StringinputPath ="D:\\ExampleDirectory\\compressed.txt";
      //Instantiating the FileInputStream
      FileInputStream inputStream = new FileInputStream(inputPath);
      String outputpath = "D:\\ExampleDirectory\\output.jpg";
      FileOutputStream outputStream = new FileOutputStream(outputpath);
      InflaterInputStream decompresser = new InflaterInputStream(inputStream);
      int contents;
      while ((contents=decompresser.read())!=-1){
         outputStream.write(contents);
      }
      //close the file
      outputStream.close();
      decompresser.close();
      System.out.println("File un-compressed.......");
   }
}

Đầu ra

File un-compressed.......