Java中的ZIP标准

本文介绍两种从ZIP格式文件(如EAR、WAR、JAR)中读取资源的方法:一是利用Classloader将文件作为资源处理;二是使用java.util.zip包进行操作。此外,还提供了向ZIP文件写入内容和更新文件的具体示例。

这样一篇入门级文章,实在没有多大技术含量,只是碰巧刚才有人问我如何读EAR或者WAR中的某个资源文件,最简单的方式以资源方式读取,另外一种则可以采用Zip API去读,实际上J2EE中我们接触到的全部部署文件都是遵循ZIP压缩标准的。明白这一点,我们就不用关注他的文件扩展名到底是什么,都可以方便的用WinZip或者WinRAR去查看其压缩包的内容。同时我们在部署一些应用时,如果我们熟悉了EAR、WAR的结构规则,我们也可以直接按照其目录结构规则用WinZip或者WinRAR组织发布的压缩文件,而不用ANT(哈哈,不是推荐替换ANT,只是让初学者可以多一条路径来理解这个过程)。下面我给出这两种方式的实现。
第一种方式,通过classloader,将zip格式中的文件当做资源来处理,提供读取每个资源的InputStream,得到这个InputStream对象我们就可以象操作普通文件一样的操作了。

None.gifpackage rookie.demo;
None.gif
None.gif
import java.io.IOException;
None.gif
import java.io.BufferedReader;
None.gif
import java.io.InputStreamReader;
ExpandedBlockStart.gifContractedBlock.gif
/** *//**
InBlock.gif * @description 演示如何读取EAR,WAR,JAR中的资源文件。
ExpandedBlockEnd.gif 
*/

ExpandedBlockStart.gifContractedBlock.gif
public class ResourceDemo dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public static void main(String[] args) dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
if (args.length < 1dot.gif{
InBlock.gif            usage();
InBlock.gif            
return;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
try dot.gif{
InBlock.gif            ClassLoader clsLoader 
= Thread.currentThread().getContextClassLoader();
InBlock.gif            BufferedReader reader 
= new BufferedReader(new InputStreamReader(clsLoader.getResourceAsStream(args[0])));
InBlock.gif            String sLine;
ExpandedSubBlockStart.gifContractedSubBlock.gif            
while ((sLine = reader.readLine()) != nulldot.gif{
InBlock.gif                System.out.println(sLine);
ExpandedSubBlockEnd.gif            }

InBlock.gif            reader.close();
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (IOException exp) dot.gif{
InBlock.gif            exp.printStackTrace();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * @description Show usage information
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public static void usage() dot.gif{
InBlock.gif        System.out.println(
"=======================================================================");
InBlock.gif        System.out.println(
" Usage: ");
InBlock.gif        System.out.println(
" java rookie.demo.ResourceDemo resourceName");
InBlock.gif        System.out.println(
"");
InBlock.gif        System.out.println(
"=======================================================================");
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}
;
None.gif


第二种方式,我们使用java.util.zip包提供的api进行文件操作,这个例子给出了简单的ZipEntry列表及读取功能。

None.gifpackage rookie.demo;
None.gif
None.gif
import java.io.IOException;
None.gif
import java.io.BufferedReader;
None.gif
import java.io.InputStreamReader;
None.gif
import java.util.Enumeration;
None.gif
import java.util.zip.*;
ExpandedBlockStart.gifContractedBlock.gif
/** *//**
InBlock.gif * @description 演示如何读取Zip文件,Zip作为Java压缩格式的标准,事实上我们所见的EAR,WAR,JAR都是Zip格式的压缩文件。
ExpandedBlockEnd.gif 
*/

ExpandedBlockStart.gifContractedBlock.gif
public class ZipDemo dot.gif{
InBlock.gif    String sFileName;
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public ZipDemo(String fName) dot.gif{
InBlock.gif        sFileName 
= fName;
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void setFileName(String fName) dot.gif{
InBlock.gif        sFileName 
= fName;
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public String getFileName() dot.gif{
InBlock.gif        
return sFileName;
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * @description List the zip file's entries
ExpandedSubBlockEnd.gif     
*/

InBlock.gif    
public void listEntries() 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
throws Exception dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
if (sFileName == null || sFileName == "")dot.gif{
InBlock.gif            
throw new Exception("Have not specified the zip file name.");
ExpandedSubBlockEnd.gif        }

InBlock.gif        ZipFile zFile 
= new ZipFile(sFileName);
ExpandedSubBlockStart.gifContractedSubBlock.gif        
for (Enumeration e = zFile.entries() ; e.hasMoreElements() ;) dot.gif{
InBlock.gif            ZipEntry zEntry 
= (ZipEntry)e.nextElement();
InBlock.gif            System.out.println(zEntry.getName());
ExpandedSubBlockEnd.gif        }

InBlock.gif        zFile.close();
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * @description Read the specified entry
InBlock.gif     * 
@param sEntry the name of the entry for reading
ExpandedSubBlockEnd.gif     
*/

InBlock.gif    
public void readEntry(String sEntry) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
throws Exception dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
if (sFileName == null || sFileName == "")dot.gif{
InBlock.gif            
throw new Exception("Have not specified the zip file name.");
ExpandedSubBlockEnd.gif        }

InBlock.gif        ZipFile zFile 
= new ZipFile(sFileName);
InBlock.gif        ZipEntry zEntry 
= zFile.getEntry(sEntry);
InBlock.gif        BufferedReader reader 
= new BufferedReader(new InputStreamReader(zFile.getInputStream(zEntry)));
InBlock.gif        String sLine;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
while ((sLine = reader.readLine()) != null)dot.gif{
InBlock.gif            System.out.println(sLine);
ExpandedSubBlockEnd.gif        }

InBlock.gif        reader.close();
InBlock.gif        zFile.close();
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public static void main(String[] args) dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
if (args.length < 1dot.gif{
InBlock.gif            usage();
InBlock.gif            
return;
ExpandedSubBlockEnd.gif        }

InBlock.gif        ZipDemo demo 
= new ZipDemo(args[0]);
ExpandedSubBlockStart.gifContractedSubBlock.gif        
try dot.gif{
InBlock.gif            BufferedReader reader 
= new BufferedReader(new InputStreamReader(System.in));
InBlock.gif            String sLine;
ExpandedSubBlockStart.gifContractedSubBlock.gif            
while ((sLine = reader.readLine()) != null && !sLine.equalsIgnoreCase("exit"&& !sLine.equalsIgnoreCase("quit"))dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif                
try dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
if (sLine.equalsIgnoreCase("help"))dot.gif{
InBlock.gif                        System.out.println(
"help\tShow this command list information.");
InBlock.gif                        System.out.println(
"list\tList the zip file entries.");
InBlock.gif                        System.out.println(
"read <entry>\tRead the specified zip file entry content.");
InBlock.gif                        System.out.println(
"open <zipfile>\tSpecify the operating zip file name.");
InBlock.gif                        System.out.println(
"name\tShow the current operating zip file name.");
ExpandedSubBlockStart.gifContractedSubBlock.gif                    }
 else if (sLine.equalsIgnoreCase("list"))dot.gif{
InBlock.gif                        demo.listEntries();
ExpandedSubBlockStart.gifContractedSubBlock.gif                    }
 else if (sLine.equalsIgnoreCase("name"))dot.gif{
InBlock.gif                        System.out.println(demo.getFileName());
ExpandedSubBlockStart.gifContractedSubBlock.gif                    }
 else if (sLine.substring(05).equalsIgnoreCase("read ")) dot.gif{
InBlock.gif                        demo.readEntry(sLine.substring(
5));
ExpandedSubBlockStart.gifContractedSubBlock.gif                    }
 else if (sLine.substring(05).equalsIgnoreCase("open ")) dot.gif{
InBlock.gif                        demo.setFileName(sLine.substring(
5));
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockStart.gifContractedSubBlock.gif                }
 catch (Exception exp) dot.gif{
InBlock.gif                    exp.printStackTrace();
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            reader.close();
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (IOException exp) dot.gif{
InBlock.gif            exp.printStackTrace();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * @description Show usage information
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public static void usage() dot.gif{
InBlock.gif        System.out.println(
"=======================================================================");
InBlock.gif        System.out.println(
" Usage: ");
InBlock.gif        System.out.println(
" java rookie.demo.ZipDemo zipFile");
InBlock.gif        System.out.println(
"");
InBlock.gif        System.out.println(
"=======================================================================");
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}
;

最后补充下,内容如何写入,下例是写入一个文本文件
None.gifpackage rookie.demo;
None.gif
None.gif
import java.io.*;
None.gif
import java.util.zip.*;
ExpandedBlockStart.gifContractedBlock.gif
public class WriteZip dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public static void main(String[] args) dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
if (args.length < 1)dot.gif{
InBlock.gif            System.out.println(
"java rookie.demo.WriteZip zipfile");
InBlock.gif            
return;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
try dot.gif{
InBlock.gif            ZipEntry zEntry 
= new ZipEntry("WEB-INF/web.xml");
InBlock.gif            
InBlock.gif            ZipOutputStream zos 
= new ZipOutputStream(new FileOutputStream(args[0]));
InBlock.gif            zos.putNextEntry(zEntry);
InBlock.gif            
InBlock.gif            PrintWriter writer 
= new PrintWriter(zos);
InBlock.gif            writer.println(
"<?xml version=\"1.0\" encoding=\"GB2312\"?>");
InBlock.gif            writer.println(
"<web-app>");
InBlock.gif            writer.println(
"</web-app>");
InBlock.gif            writer.close();
InBlock.gif            zos.close();
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (Exception exp) dot.gif{
InBlock.gif            exp.printStackTrace();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

更新包中某一个文件,下面更新一个文本文件
None.gifpackage rookie.demo;
None.gif
None.gif
import java.io.*;
None.gif
import java.util.*;
None.gif
import java.util.zip.*;
ExpandedBlockStart.gifContractedBlock.gif
public class PipeZip dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public static void main(String[] args) dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
if (args.length < 1)dot.gif{
InBlock.gif            System.out.println(
"java rookie.demo.PipeZip zipfile");
InBlock.gif            
return;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
try dot.gif{
InBlock.gif            String sFileName 
= args[0];
InBlock.gif            File file 
= new File(sFileName);
InBlock.gif            File tFile 
= new File(sFileName + ".00000"); // 临时文件
InBlock.gif
            file.renameTo(tFile);
InBlock.gif            
byte[] buf = new byte[1024];
InBlock.gif
InBlock.gif            ZipOutputStream zos 
= new ZipOutputStream(new FileOutputStream(sFileName));
InBlock.gif            BufferedOutputStream bos 
= new BufferedOutputStream(zos);
InBlock.gif
InBlock.gif            ZipFile zFile 
= new ZipFile(tFile);
ExpandedSubBlockStart.gifContractedSubBlock.gif            
for (Enumeration e = zFile.entries() ; e.hasMoreElements() ;) dot.gif{
InBlock.gif                ZipEntry zEntry 
= (ZipEntry)e.nextElement();
ExpandedSubBlockStart.gifContractedSubBlock.gif                
if (zEntry.getName().equals("WEB-INF/web.xml")) dot.gif{
InBlock.gif                    PrintWriter writer 
= new PrintWriter(bos);
InBlock.gif                    zEntry 
= new ZipEntry(zEntry.getName());
InBlock.gif                    zos.putNextEntry(zEntry);
InBlock.gif                    writer.println(
"<?xml version=\"1.0\" encoding=\"GB2312\"?>");
InBlock.gif                    writer.println(
"<web-app>");
InBlock.gif                    writer.println(
"<servlet/>");
InBlock.gif                    writer.println(
"</web-app>");
InBlock.gif                    writer.flush();
ExpandedSubBlockStart.gifContractedSubBlock.gif                }
 else dot.gif{
InBlock.gif                    BufferedInputStream bis 
= new BufferedInputStream(zFile.getInputStream(zEntry));
InBlock.gif                    zEntry 
= new ZipEntry(zEntry.getName());
InBlock.gif                    zos.putNextEntry(zEntry);
InBlock.gif                
InBlock.gif                    
int count; 
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
while ((count = bis.read(buf, 01024)) > -1dot.gif{
InBlock.gif                        bos.write(buf, 
0, count);
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    
//zos.closeEntry();
InBlock.gif
                    bis.close();
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            zFile.close();
InBlock.gif            bos.close();
InBlock.gif            zos.close();
InBlock.gif
InBlock.gif            tFile.delete();
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (Exception exp) dot.gif{
InBlock.gif            exp.printStackTrace();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值