Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีแตกไฟล์ที่บีบอัด (Un-compress) ใน Java

Java มอบคลาสชื่อ InflaterInputStream ใช้สำหรับแตกไฟล์ที่บีบอัด (un-compress)

เมธอด read() ของคลาสนี้อ่านไบต์เดียวของข้อมูลที่บีบอัดจาก input stream เพื่อแตกไฟล์ที่บีบอัดด้วยเมธอดนี้ −

  • สร้างอ็อบเจกต์ FileInputStream โดยส่งพาธของไฟล์ที่บีบอัดในรูป String เป็นพารามิเตอร์ให้ constructor
  • สร้างอ็อบเจกต์ FileOutputStream โดยส่งพาธของไฟล์เอาต์พุต (ไฟล์รูปภาพที่แตกแล้ว) ในรูป String เป็นพารามิเตอร์ให้ constructor
  • สร้างอ็อบเจกต์ InflaterInputStream โดยส่ง FileInputStream ที่สร้างไว้ข้างต้น เป็นพารามิเตอร์ให้ constructor
  • จากนั้น อ่านเนื้อหาของ InflaterInputStream และเขียนโดยใช้เมธอด write() ของคลาส FileOutputStream

ตัวอย่างโค้ด

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 {
        String inputPath = "D:\\ExampleDirectory\\compressed.txt";
        // สร้าง 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);
        }
        
        // ปิดไฟล์
        outputStream.close();
        decompresser.close();
        
        System.out.println("File un-compressed.......");
    }
}

ผลลัพธ์

File un-compressed.......