龙空技术网

java实现文件压缩

天子小门生 105

前言:

眼前各位老铁们对“java图片无损压缩算法”大体比较着重,咱们都需要了解一些“java图片无损压缩算法”的相关知识。那么小编在网络上收集了一些对于“java图片无损压缩算法””的相关文章,希望姐妹们能喜欢,我们一起来学习一下吧!

最近碰到个需要打包文件成压缩包的项目,需要注意压缩输出流ZipOutputStream应该在finally中关闭,提前关闭或者不关闭都会导致压缩失败。

下面直接上代码:

//递归压缩文件工具类public class ZipUitls {    /**     *     * @param zos  生成的压缩文件     * @param sourcesFile 需要压缩的文件,可以是文件夹     * @param name  保存到压缩文件的文件名称     * @throws IOException     */    public void fileToZip(ZipOutputStream zos,File sourcesFile,String name) throws IOException {        //遍历文件夹的文件        File[] files = sourcesFile.listFiles();        for (File file : files) {            //如果是文件,则压缩到zos压缩文件中            if (file.isFile()){                //文件输入流                FileInputStream inputStream = new FileInputStream(file);                zos.putNextEntry(new ZipEntry(name + File.separator  + file.getName()));                byte[] bytes = new byte[2048];                int length;                while ((length = inputStream.read(bytes)) != -1){                    zos.write(bytes);                }            }else {                //如果是文件夹,则递归                if (file.listFiles().length == 0){  //如果只是空文件夹,则只保留一个目录                                        zos.putNextEntry(new ZipEntry(name + File.separator + file.getName() + "/"));                }                //如果文件夹里面有内容,则递归                fileToZip(zos,file,name + File.separator + file.getName());            }        }    }}
//测试类public void testZip() throws IOException {        long start = System.currentTimeMillis();        System.out.println(start);        ZipUitls zipUitls = new ZipUitls();        ZipOutputStream zos = null;        FileOutputStream fos = null;        try {          	//压缩输出的文件为:D:\ceshi.zip            fos = new FileOutputStream("D:" + File.separator + "ceshi.zip");            zos = new ZipOutputStream(fos);          	//压缩源文件            File sourceFile = new File("D:" + File.separator + "hello");          	//调用ZipUitls中的压缩方法            zipUitls.fileToZip(zos,sourceFile,sourceFile.getName());        }catch (FileNotFoundException e) {            throw new RuntimeException(e);        }finally {          //ZipOutputStream压缩输出流在finally处关闭,不然压缩失败            if (zos != null){                zos.close();            }            if (fos !=  null){                fos.close();            }        }        long end = System.currentTimeMillis();        System.out.println(end);        System.out.println(end - start);    }

标签: #java图片无损压缩算法