java.util.zip.ZipInputStream类练习

Code:
  1. package Flow;   
  2. import java.io.*;   
  3. import java.awt.*;   
  4. import java.awt.event.ActionEvent;   
  5. import java.awt.event.ActionListener;   
  6.   
  7. import javax.swing.*;   
  8. import javax.swing.filechooser.FileFilter;   
  9.   
  10. import java.util.*;   
  11. import java.util.zip.ZipEntry;   
  12. import java.util.zip.ZipInputStream;   
  13. public class ZipTest {   
  14.   
  15.     /**  
  16.      * @param args  
  17.      */  
  18.     public static void main(String[] args) {   
  19.         // TODO Auto-generated method stub   
  20.         ZipTestFrame frame = new ZipTestFrame();   
  21.         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);   
  22.         frame.setVisible(true);   
  23.     }   
  24.   
  25. }   
  26.   
  27. class ZipTestFrame extends JFrame{   
  28.     private static final int DEFAULT_HEIGHT = 300;   
  29.     private static final int DEFAULT_WIDTH = 400;   
  30.     private JComboBox fileCombo;   
  31.     private JTextArea fileTest;   
  32.     private String zipname;   
  33.   
  34.     public ZipTestFrame(){   
  35.         setTitle("ZipTest");   
  36.         setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);   
  37.         //add the menu and the Open and Exit items   
  38.         JMenuBar menuBar = new JMenuBar();   
  39.         JMenu menu = new JMenu("File");   
  40.            
  41.         JMenuItem openItem = new JMenuItem("Open");   
  42.         menu.add(openItem);   
  43.         openItem.addActionListener(new OpenAction());   
  44.            
  45.         JMenuItem exitItem = new JMenuItem("Exit");   
  46.         menu.add(exitItem);   
  47.         exitItem.addActionListener(new ActionListener(){   
  48.             public void actionPerformed(ActionEvent e){   
  49.                 System.exit(0);   
  50.             }   
  51.         });   
  52.            
  53.         menuBar.add(menu);   
  54.         setJMenuBar(menuBar);   
  55.            
  56.         //add the text area and combo box   
  57.         fileTest = new JTextArea();   
  58.         fileCombo = new JComboBox();   
  59.         fileCombo.addActionListener(new ActionListener(){   
  60.             public void actionPerformed(ActionEvent e){   
  61.                 loadZipFile((String)fileCombo.getSelectedItem());   
  62.             }   
  63.         });   
  64.         add(fileCombo,BorderLayout.SOUTH);   
  65.         add(fileTest,BorderLayout.CENTER);   
  66.            
  67.     }   
  68.        
  69.     /**  
  70.      * This is the listener for the file->open menu item  
  71.      * @param name  
  72.      */  
  73.     //   
  74.     public class OpenAction implements ActionListener{   
  75.         public void actionPerformed(ActionEvent e){   
  76.             //prompt the user for a zip file   
  77.             JFileChooser chooser = new JFileChooser();   
  78.             chooser.setCurrentDirectory(new File("."));   
  79.             FileFilter filter = new ExtensionFileFilter();   
  80.             ((ExtensionFileFilter) filter).addExtention(".zip");   
  81.             ((ExtensionFileFilter) filter).addExtention(".jar");   
  82.             ((ExtensionFileFilter) filter).setDescription("ZIP archives");   
  83.             chooser.setFileFilter(filter);   
  84.             int r = chooser.showOpenDialog(ZipTestFrame.this);   
  85.             if(r == JFileChooser.APPROVE_OPTION){   
  86.                 zipname = chooser.getSelectedFile().getPath();   
  87.                 //System.out.println(zipname);   
  88.                 scanZipFile();   
  89.             }   
  90.         }   
  91.     }   
  92.        
  93.     /**  
  94.      * Scans the contents of the zip archive and populates  
  95.      */  
  96.     private void scanZipFile() {   
  97.         // TODO Auto-generated method stub   
  98.         fileCombo.removeAll();   
  99.         ZipInputStream zin = null;   
  100.         try {   
  101.             zin = new ZipInputStream(new FileInputStream(zipname));   
  102.             ZipEntry entry = null;   
  103.             while((entry = zin.getNextEntry()) != null){   
  104.                 fileCombo.addItem(entry.getName());   
  105.                    
  106.                 zin.closeEntry();   
  107.             }   
  108.         } catch (FileNotFoundException e) {   
  109.             // TODO Auto-generated catch block   
  110.             e.printStackTrace();   
  111.         }catch(IOException e1){   
  112.             e1.printStackTrace();   
  113.         }finally{   
  114.             if(zin != null){   
  115.                 try {   
  116.                     zin.close();   
  117.                 } catch (IOException e) {   
  118.                     // TODO Auto-generated catch block   
  119.                     e.printStackTrace();   
  120.                 }   
  121.             }   
  122.         }   
  123.            
  124.     }   
  125.        
  126.     /**  
  127.      * Loads a file from the zip archive into the text area  
  128.      * @param name the name of the file in the archive  
  129.      */  
  130.     public void loadZipFile(String name){   
  131.         // TODO Auto-generated method stub   
  132.         ZipInputStream zin = null;   
  133.         try {   
  134.             zin = new ZipInputStream(new FileInputStream(zipname));   
  135.             ZipEntry entry;   
  136.             fileTest.setText("");   
  137.                
  138.             //find entry with matching name in archive   
  139.             while((entry = zin.getNextEntry()) != null){   
  140.                 //read entry with matching name in archive   
  141.                 BufferedReader in = new BufferedReader(new InputStreamReader(zin));   
  142.                 String line;   
  143.                 while((line = in.readLine()) != null){   
  144.                     fileTest.append(line);   
  145.                     fileTest.append("/n");   
  146.                 }   
  147.             }   
  148.                
  149.                
  150.         } catch (FileNotFoundException e) {   
  151.             // TODO Auto-generated catch block   
  152.             e.printStackTrace();   
  153.         }catch(IOException e1){   
  154.             e1.printStackTrace();   
  155.         }finally{   
  156.             if(zin != null){   
  157.                 try {   
  158.                     zin.close();   
  159.                 } catch (IOException e) {   
  160.                     // TODO Auto-generated catch block   
  161.                     e.printStackTrace();   
  162.                 }   
  163.             }   
  164.         }   
  165.     }   
  166. }   
  167.   
  168.   
  169. class ExtensionFileFilter extends FileFilter{   
  170.        
  171.     private String description = "";   
  172.     private ArrayList<String> extensions = new ArrayList<String>();   
  173.        
  174.     public boolean accept(File pathname) {   
  175.         // TODO Auto-generated method stub   
  176.         if(pathname.isDirectory()){   
  177.             return true;   
  178.         }   
  179.         String name = pathname.getName().toLowerCase();   
  180.            
  181.         //check if the file name ends with any of the extensions   
  182.         for(String e : extensions){   
  183.             if(name.endsWith(e))   
  184.                 return true;   
  185.         }   
  186.             return false;   
  187.            
  188.     }   
  189.   
  190.     /**  
  191.      * Sets a description for the file set that this file filter recognizes  
  192.      * @param string a description for the file set  
  193.      */  
  194.     public void setDescription(String string) {   
  195.         // TODO Auto-generated method stub   
  196.         this.description = string;   
  197.     }   
  198.   
  199.     /**  
  200.      * Adds an extension that this file Filter recognizes  
  201.      * @param string a file extension (suchi as ".txt" or "txt")  
  202.      */  
  203.     public void addExtention(String string) {   
  204.         // TODO Auto-generated method stub   
  205.         if(!string.startsWith(".")){   
  206.             string = "." + string;   
  207.         }   
  208.         extensions.add(string.toLowerCase());   
  209.     }   
  210.   
  211.     /**  
  212.      * Returns a decription for the file set that this file  
  213.      * filter recognizes  
  214.      * @return a description for the file set  
  215.      */  
  216.     public String getDescription() {   
  217.         // TODO Auto-generated method stub   
  218.         return this.description;   
  219.     }}  

处理ZIP文件的类是在java.util.zip包中而不是在java.io包中。记住啊。

但是呢,ZIP和GZIP类还是java.io.FilteInputStream和java.io.FilterOutputStream的子类。

java.utio.zip包同样也包含了用于计算循环冗余码校验的类。(CRC校验法)。

每个ZIP文件都有文件头,其中包含了诸如文件名和使用的压缩方法等信息。在java中,通过将一个FileInputStream传给ZipInputStream构造器,可以用ZipInputStream类来读取一个ZIP文件。随后需要去查看压缩文件中的每个独立的条目。getNextEntry()方法(恩,很关键的一个方法)可以返回一个描述该条目的ZipEntry类型的对象。(也就是返回一个代表ZIP文件下的一个子文件的类ZipEntry的对象)。ZipInputStream的read方法进行了修改,当达到条目的末尾(不是ZIP文件的末尾哦)时返回-1。随后,必须调用closeEntry()方法来关闭该条目,接着读取下一条目。如上面代码中的一段用来顺序读取ZIP文件条目的代码:

Code:
  1. private void scanZipFile() {   
  2.         // TODO Auto-generated method stub   
  3.         fileCombo.removeAll();   
  4.         ZipInputStream zin = null;   
  5.         try {   
  6.             zin = new ZipInputStream(new FileInputStream(zipname));   
  7.             ZipEntry entry = null;   
  8.             while((entry = zin.getNextEntry()) != null){   
  9.                 fileCombo.addItem(entry.getName());   
  10.                    
  11.                 zin.closeEntry();   
  12.             }   
  13.         } catch (FileNotFoundException e) {   
  14.             // TODO Auto-generated catch block   
  15.             e.printStackTrace();   
  16.         }catch(IOException e1){   
  17.             e1.printStackTrace();   
  18.         }finally{   
  19.             if(zin != null){   
  20.                 try {   
  21.                     zin.close();   
  22.                 } catch (IOException e) {   
  23.                     // TODO Auto-generated catch block   
  24.                     e.printStackTrace();   
  25.                 }   
  26.             }   
  27.         }   
  28.            
  29.     }  

要读取ZIP条目的内容(是内容哦,也就是ZIP文件下的文件里的内容),很可能不愿意使用原来的read方法。通常 会使用更适宜的流过滤器的方法。例如,读取ZIP文件中的一个文本文件,可以使用一下循环:

Code:
  1. BufferedReader in = new BufferedReader(new InputStreamReader(zin));   
  2. String s;   
  3. while((s = in.readLine()) != null){   
  4.            do something with s;   
  5. }  

如以上程序中的一段代码:

Code:
  1. public void loadZipFile(String name){   
  2.         // TODO Auto-generated method stub   
  3.         ZipInputStream zin = null;   
  4.         try {   
  5.             zin = new ZipInputStream(new FileInputStream(zipname));   
  6.             ZipEntry entry;   
  7.             fileTest.setText("");   
  8.                
  9.             //find entry with matching name in archive   
  10.             while((entry = zin.getNextEntry()) != null){   
  11.                 //read entry with matching name in archive   
  12.                 BufferedReader in = new BufferedReader(new InputStreamReader(zin));   
  13.                 String line;   
  14.                 while((line = in.readLine()) != null){   
  15.                     fileTest.append(line);   
  16.                     fileTest.append("/n");   
  17.                 }   
  18.             }   
  19.                
  20.                
  21.         } catch (FileNotFoundException e) {   
  22.             // TODO Auto-generated catch block   
  23.             e.printStackTrace();   
  24.         }catch(IOException e1){   
  25.             e1.printStackTrace();   
  26.         }finally{   
  27.             if(zin != null){   
  28.                 try {   
  29.                     zin.close();   
  30.                 } catch (IOException e) {   
  31.                     // TODO Auto-generated catch block   
  32.                     e.printStackTrace();   
  33.                 }   
  34.             }   
  35.         }   
  36.     }   
  37. }  

当向一个ZIP文件写入时需要打开一个构造器中包含FileOutputStream的ZipOutputStream文件流。对于每一条希望植入ZIP文件的条目,都要创建一个ZipEntry对象。只要把文件名传给ZipEntry构造器,它将会自动设置参数(注意是自动设置哦)。诸如文件日期和压缩方法等等。但是也可以自己覆盖这些参数。对于写出可以查看ZIP,写入会了写出一定是没有问题了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值