java压缩文件
利用org.apche.tools.zip.ZipOutputStream可以很好的将文件压缩保存,下面的例子是利用递归的方法将文件压缩的例子
- import java.io.*;
- import org.apache.tools.zip.ZipEntry;
- import org.apache.tools.zip.ZipOutputStream;
- 将夜www.jiangyea.com
- /**
- * 提供文件压缩的常用方法
- */
- public class ZipUtil {
- /**
- *
- * @param src 源文件或者目录
- * @param dest 压缩文件的目标路径
- */
- public static void zip(String src,String dest){
- ZipOutputStream out = null;
- try {
- File outFile = new File(dest);
- out = new ZipOutputStream(outFile);
- File fileDirectory = new File(src);
- if(fileDirectory.isFile()){
- zipFileOrDirectory(out,fileDirectory,"");
- }else{
- File [] entries = fileDirectory.listFiles();
- zipFileOrDirectory(out, fileDirectory, "");
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally{
- if(out != null){
- try {
- out.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- private static void zipFileOrDirectory(ZipOutputStream out,File fileOrDirectory,String curPath){
- FileInputStream in = null;
- try {
- if(!fileOrDirectory.isDirectory()){//判断当前不是一个目录级
- byte[] buffer = new byte[4096];
- int bytes_read;
- in = new FileInputStream(fileOrDirectory);
- ZipEntry entry = new ZipEntry(curPath + fileOrDirectory.getName());
- out.putNextEntry(entry);
- while((bytes_read = in.read(buffer)) != -1){
- //buffer=要写入的数据,0=偏移量,bytes_read=要写入的字节长度
- out.write(buffer, 0 ,bytes_read);
- }
- out.closeEntry();
- }else{
- File[] entries = fileOrDirectory.listFiles();
- for(int i = 0;i < entries.length;i++){
- zipFileOrDirectory(out, entries[i], curPath + fileOrDirectory.getName() + "/");//递归分解目录中的文件
- }
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally{
- if(in != null){
- try {
- in.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- }
重生之大文豪 www.dwhao.com