Java | 用java写一个解压程序

编写目的:

  • 把一个压缩文件进行解压操作

代码内容:

public class ZipStream1 {
    public static void main(String[] args) throws IOException {
    	// 被压缩文件
        File src = new File("D:\\SteamTools-2.8.6.zip");
		// 压缩文件
        File dest = new File("D:\\bbb");
		// 解压方法
        zipFile(src,dest);
    }

    private static void zipFile(File src, File dest) throws IOException {
    	// 建立目录
        dest.mkdirs();
        // 创建压缩流对象
        ZipInputStream zip = new ZipInputStream(new FileInputStream(src));
		// 标记读取的对象
        ZipEntry entry;
        while ((entry = zip.getNextEntry()) != null) {
        	// 是文件夹
            if (entry.isDirectory()) {
                File file = new File(dest, entry.toString());
                file.mkdirs();
            } else {
            	// 是文件
                FileOutputStream fos = new FileOutputStream(new File(dest, entry.toString()));

                int b;
                while ((b = zip.read()) != -1) {
                    fos.write(b);
                }
                fos.close();
                zip.closeEntry();
            }
        }
        zip.close();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java的ZipInputStream和FileOutputStream类来缩一个ZIP文件。以下是一个示例代码: ```java import java.io.*; import java.util.zip.*; public class Unzip { public static void main(String[] args) { String zipFile = "path/to/your/zip/file.zip"; String outputFolder = "path/to/your/output/folder/"; try { // Create output folder if it doesn't exist File folder = new File(outputFolder); if (!folder.exists()) { folder.mkdirs(); } // Open the zip file FileInputStream fis = new FileInputStream(zipFile); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); // Extract files from the zip file ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String filename = entry.getName(); File outputFile = new File(outputFolder + filename); // Create parent directories for the output file if necessary File parent = outputFile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } // Write the contents of the entry to the output file FileOutputStream fos = new FileOutputStream(outputFile); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buffer = new byte[1024]; int count; while ((count = zis.read(buffer)) != -1) { bos.write(buffer, 0, count); } bos.flush(); bos.close(); } // Close the input stream zis.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码将zipFile路径下的ZIP文件缩到outputFolder路径下。你需要自行替换这些路径以适应你自己的环境。同时,这个示例代码只能在Windows环境下使用。如果你需要在其他操作系统下使用,需要更新路径分隔符和行分隔符。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值