springboot Java 7z 高效率壓縮文件(org.apache.commons.compress.archivers.sevenz)


看一下戰果

直接上代碼

<--maven配置-->

       
     <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.12</version> </dependency> <dependency> <groupId>org.tukaani</groupId> <artifactId>xz</artifactId> <version>1.5</version> </dependency>
public class CompressUtil {
    // 測試
    public static void main(String[] args) {
        String path = "D:\\Test\\pdf\\2020-01-08\\92b4809959d5478ba5ad5dc676444c06.pdf";
//        path = "D:\\Test\\pdf\\2020-01-08\\12.txt";
        String path2 = "D:\\Test\\pdf\\2020-01-08\\92b4809959d5478ba5ad5dc676444c06z.7z";

        try {
            Compress7z(path,path2);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

    }

    /**
     * 7z文件壓縮
     *
     * @param inputFile  待壓縮文件夾/文件名
     * @param outputFile 生成的壓縮包名字
     */

    public static void Compress7z(String inputFile, String outputFile) throws Exception {
        File input = new File(inputFile);
        if (!input.exists()) {
            throw new Exception(input.getPath() + "待壓縮文件不存在");
        }
        SevenZOutputFile out = new SevenZOutputFile(new File(outputFile));

        compress(out, input, null);
        out.close();
    }

    /**
     * @param name 壓縮文件名,可以寫為null保持默認
     */
    //遞歸壓縮
    public static void compress(SevenZOutputFile out, File input, String name) throws IOException {
        if (name == null) {
            name = input.getName();
        }
        SevenZArchiveEntry entry = null;
        //如果路徑為目錄(文件夾)
        if (input.isDirectory()) {
            //取出文件夾中的文件(或子文件夾)
            File[] flist = input.listFiles();

            if (flist.length == 0)//如果文件夾為空,則只需在目的地.7z文件中寫入一個目錄進入
            {
                entry = out.createArchiveEntry(input,name + "/");
                out.putArchiveEntry(entry);
            } else//如果文件夾不為空,則遞歸調用compress,文件夾中的每一個文件(或文件夾)進行壓縮
            {
                for (int i = 0; i < flist.length; i++) {
                    compress(out, flist[i], name + "/" + flist[i].getName());
                }
            }
        } else//如果不是目錄(文件夾),即為文件,則先寫入目錄進入點,之后將文件寫入7z文件中
        {
            FileInputStream fos = new FileInputStream(input);
            BufferedInputStream bis = new BufferedInputStream(fos);
            entry = out.createArchiveEntry(input, name);
            out.putArchiveEntry(entry);
            int len = -1;
            //將源文件寫入到7z文件中
            byte[] buf = new byte[1024];
            while ((len = bis.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            bis.close();
            fos.close();
            out.closeArchiveEntry();
        }
    }

}


免責聲明!

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



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