六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 56|回复: 0

java文件处理之压缩,分割

[复制链接]

升级  30%

3

主题

3

主题

3

主题

童生

Rank: 1

积分
15
 楼主| 发表于 2013-1-15 02:57:09 | 显示全部楼层 |阅读模式
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/** *//**
*
* @author VickenYang
* 文件处理工具
*/
public class FileProcessor ...{
   
    public static void createZipFile(File from,File to) throws Exception ...{
        if(!from.isFile())...{
            throw new Exception("file not exists"+from.getAbsolutePath());
        }
        if(to.isFile())...{
            throw new Exception("file already exists"+to.getAbsolutePath());
        }
        else...{
            to.createNewFile();
        }
        
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(to));
        ZipEntry ze = null;
        byte[] buf = new byte[1024];
        int readLen = 0;
        ze = new ZipEntry(from.getAbsolutePath());
        ze.setSize(from.length());
        ze.setTime(from.lastModified());
        zos.putNextEntry(ze);
        InputStream is = new BufferedInputStream(new FileInputStream(from));
        while ((readLen=is.read(buf, 0, 1024))!=-1) ...{
            zos.write(buf, 0, readLen);
        }
        is.close();
        zos.close();
    }
   
    public static void decompressZipFile(File from,File to) throws Exception...{
        if(!from.isFile())...{
            throw new Exception("file not exists"+from.getAbsolutePath());
        }
        if(!to.isDirectory())...{
            throw new Exception("file not directory"+to.getAbsolutePath());
        }
        ZipFile zfile = new ZipFile(from.getAbsoluteFile());
        Enumeration zList = zfile.entries();
        ZipEntry ze=null;
        byte[] buf=new byte[1024];
        while(zList.hasMoreElements())...{
            ze=(ZipEntry)zList.nextElement();
            if(ze.isDirectory())...{
                continue;
            }
            String[] zet = ze.getName().replace('\', '/').split("/");
            OutputStream os=new BufferedOutputStream(new FileOutputStream(to.getAbsoluteFile()+zet[zet.length-1]));
            InputStream is=new BufferedInputStream(zfile.getInputStream(ze));
            int readLen=0;
            while ((readLen=is.read(buf, 0, 1024))!=-1) ...{
                os.write(buf, 0, readLen);
            }
            is.close();
            os.close();
        }
        zfile.close();
    }
}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表