美文网首页
安卓开发文件和文件压缩成zip文件

安卓开发文件和文件压缩成zip文件

作者: 510bb14393e1 | 来源:发表于2022-05-06 08:21 被阅读0次
    private static void toZip(String srcFileString, String zipFileString){
            FileOutputStream fos1=null;
            ZipOutputStream zip=null;
            try{
                 fos1 = new FileOutputStream(new File(zipFileString));
                 zip= new ZipOutputStream(fos1);
                File f = new File(srcFileString);
                compress(f, zip, f.getName());
                zip.flush();
                zip.close();
                fos1.close();
            } catch (Exception e) {
                try {
                    if(zip!=null)zip.close();
                    if(fos1!=null)fos1.close();
                } catch (IOException ee) {}
                
            }
        }
        private static void compress(File sourceFile, ZipOutputStream zos, String name) throws Exception {
            int  BUFFER_SIZE = 2 * 1024;
            byte[] buf = new byte[BUFFER_SIZE];
            if (sourceFile.isFile()) {
                // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
                zos.putNextEntry(new ZipEntry(name));
                // copy文件到zip输出流中
                int len;
                FileInputStream in = new FileInputStream(sourceFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                // Complete the entry
                zos.closeEntry();
                in.close();
            } else {
                File[] listFiles = sourceFile.listFiles();
                if (listFiles == null || listFiles.length == 0) {
                        // 空文件夹的处理
                        zos.putNextEntry(new ZipEntry(name + "/"));
                        // 没有文件,不需要文件的copy
                        zos.closeEntry();
    
                } else {
                    for (File file : listFiles) {
                            compress(file, zos, name + "/" + file.getName());
                    }
                }
            }
            }
    

    使用方法

    public static void main(String[] args) 
        {
            
            toZip("/sdcard/temp","/sdcard/myzip.zip");
            System.out.println("ok");
    
        }
    

    相关文章

      网友评论

          本文标题:安卓开发文件和文件压缩成zip文件

          本文链接:https://www.haomeiwen.com/subject/puyayrtx.html