Java將文本文件壓縮為tar.gz


    /**
     * @功能描述 壓縮tar.gz 文件
     * @param sources 源文件集合
     * @param outPath 目標文件名稱 無后綴的 例子 G:\backup\logstash-2020.04.22
     * @return 返回壓縮結果
     * @throws Exception
     */
    public static void packet(String[] sources, String outPath) throws Exception {
        // gz文件 名稱  TAR GZ 就是 .tar.gz
        String gzPath = String.format("%s%s%s",outPath, TAR, GZ);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        TarArchiveOutputStream tarArchiveOutputStream = null;
        GZIPOutputStream gzipOutputStream = null;
        try {
            tarArchiveOutputStream = new TarArchiveOutputStream(byteArrayOutputStream);
            // 將所有文件打包成 tar文件
            try {
                for (String source : sources) {
                    File file = new File(source);
                    tarArchiveOutputStream.putArchiveEntry(new TarArchiveEntry(file, file.getName()));
                    IOUtils.copy(new FileInputStream(file), tarArchiveOutputStream);
                    tarArchiveOutputStream.closeArchiveEntry();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(tarArchiveOutputStream != null) {
                    tarArchiveOutputStream.flush();
                    tarArchiveOutputStream.close();
                }
            }
            gzipOutputStream = new GZIPOutputStream(new FileOutputStream(gzPath));
            gzipOutputStream.write(byteArrayOutputStream.toByteArray());
        } finally {
            if(byteArrayOutputStream != null) {
                byteArrayOutputStream.close();
            }
            if(gzipOutputStream != null) {
                gzipOutputStream.flush();
                gzipOutputStream.close();
            }
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM