怎么用java实现压缩文件

34次阅读
没有评论

共计 1418 个字符,预计需要花费 4 分钟才能阅读完成。

你可以使用 Java 的 ZipOutputStream 类来压缩文件。下面是一个简单的例子:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileExample {public static void main(String[] args) {String sourcePath = "path/to/source/file";
        String zipFilePath = "path/to/zip/file.zip";

        zipFile(sourcePath, zipFilePath);
    }

    public static void zipFile(String sourcePath, String zipFilePath) {try {File sourceFile = new File(sourcePath);
            FileOutputStream fos = new FileOutputStream(zipFilePath);
            ZipOutputStream zipOut = new ZipOutputStream(fos);

            addFileToZip(sourceFile, zipOut, "");

            zipOut.close();
            fos.close();} catch (IOException e) {e.printStackTrace();
        }
    }

    public static void addFileToZip(File file, ZipOutputStream zipOut, String parentDir) throws IOException {String path = parentDir + file.getName();
        if (file.isDirectory()) {File[] files = file.listFiles();
            for (File nestedFile : files) {addFileToZip(nestedFile, zipOut, path + "/");
            }
        } else {byte[] buffer = new byte[1024];
            FileInputStream fis = new FileInputStream(file);
            zipOut.putNextEntry(new ZipEntry(path));

            int length;
            while ((length = fis.read(buffer)) > 0) {zipOut.write(buffer, 0, length);
            }

            zipOut.closeEntry();
            fis.close();}
    }
}

在上述示例中,zipFile()方法接受源文件路径和目标 ZIP 文件路径。它打开源文件,创建一个 ZipOutputStream 并将源文件添加到压缩包。

addFileToZip()方法是一个递归方法,它将源文件或目录添加到压缩包中。如果源文件是目录,它将遍历目录中的所有文件并递归调用自身。如果源文件是普通文件,它将读取文件内容并将其写入压缩包中。

请确保将 sourcePath 替换为要压缩的文件或目录的实际路径,并将 zipFilePath 替换为要创建的 ZIP 文件的路径。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-16发表,共计1418字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)