【Java】压缩包解压实现过程
    		       		warning:
    		            这篇文章距离上次修改已过429天,其中的内容可能已经有所变动。
    		        
        		                
                在Java中,可以使用java.util.zip包中的类来解压缩文件。以下是一个简单的示例,展示了如何使用ZipInputStream类解压缩ZIP文件。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
 
public class UnzipUtility {
    public static void unzip(String zipFilePath, String destDir) throws IOException {
        FileInputStream fis = new FileInputStream(zipFilePath);
        ZipInputStream zis = new ZipInputStream(fis);
        ZipEntry ze = zis.getNextEntry();
 
        byte[] buffer = new byte[1024];
        int length;
        
        while (ze != null) {
            String fileName = ze.getName();
            FileOutputStream fos = new FileOutputStream(destDir + File.separator + fileName);
            while ((length = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            fos.close();
            zis.closeEntry();
            ze = zis.getNextEntry();
        }
 
        zis.closeEntry();
        zis.close();
        fis.close();
    }
 
    public static void main(String[] args) {
        try {
            unzip("/path/to/your/zipfile.zip", "/path/to/extract");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}这段代码定义了一个unzip方法,它接受ZIP文件的路径和解压目标目录作为参数。然后使用ZipInputStream来读取ZIP文件,并逐个读取其中的条目。对于每个条目,它创建一个文件输出流,将数据写入目标目录中的对应文件,然后关闭流和条目。最后,关闭整个ZIP流。
评论已关闭