java之壓縮流(ZipOutputStream)

  1、文件壓縮,是頗有必要的,咱們在進行文件,傳輸過程當中,不少時候都是,都是單個文件單個文件發送接收,可是當數據量特別大,或者文件數量比較多的時候,這個時候就能夠考慮文件壓縮。測試

  2、優點:文件壓縮事後,只須要進行一次文件的傳輸就能夠了。減小頻繁發送的問題。缺點:文件大小會變大,若是傳輸過程當中斷了,風險較大。spa

  3、實現:code

/** * 提供給用戶使用的基本壓縮類 * @param srcPath * @param outPath * @throws IOException */
    public static void compressFile(String srcPath, String outPath) throws IOException { //讀取源文件
        File srcFile = new File(srcPath); //判斷輸出路徑是否正確
        File outFile = new File(outPath); //若是隻是路勁加入對應的壓縮名稱
        if (outFile.isDirectory()) { //用"/"做文判斷標準
            if (outPath.endsWith(File.separator)) { outPath += srcFile.getName().split("\\.")[0] + ".zip"; } else { outPath += File.separator + srcFile.getName().split("\\.")[0] + ".zip"; } } //讀取文件流
        FileOutputStream fileOutputStream = new FileOutputStream(outPath); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream); //壓縮文件
 compressFile(srcFile, srcFile.getName(),zipOutputStream); //關閉流
 zipOutputStream.close(); fileOutputStream.close(); } /** * 迭代方式進行文件壓縮 * @param file * @param fileName * @param outputStream * @throws IOException */
    private static void compressFile(File file, String fileName, final ZipOutputStream outputStream) throws IOException { //若是是目錄
        if (file.isDirectory()) { //建立文件夾
            outputStream.putNextEntry(new ZipEntry(fileName+"/")); //迭代判斷,而且加入對應文件路徑
            File[] files = file.listFiles(); Iterator<File> iterator = Arrays.asList(files).iterator(); while (iterator.hasNext()) { File f = iterator.next(); compressFile(f, fileName+"/"+f.getName(), outputStream); } } else { //建立文件
            outputStream.putNextEntry(new ZipEntry(fileName)); //讀取文件並寫出
            FileInputStream fileInputStream = new FileInputStream(file); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); byte[] bytes = new byte[1024]; int n; while ((n = bufferedInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, n); } //關閉流
 fileInputStream.close(); bufferedInputStream.close(); } }

  4、測試:blog

public static void main(String[] args) throws IOException { compressFile("D:\\srv", "D:\\"); }

  5、效果仍是能夠,此方式根據須要修改!ip

相關文章
相關標籤/搜索