Java压缩/解压文件的实现代码
用java压缩/解压文件:
importjava.io.*; importjava.awt.*; importjava.awt.event.*; importjava.util.*; importjava.util.zip.*; importjavax.swing.*; //从压缩包中提取文件 publicclassZipExtractDemoextendsJFrame{ JFileChooserfileChooser;//文件选择器 JTextFieldjtfTarget;//待解压文件路径 JButtonjbSelected;//选择文件按钮 JListfiles;//信息显示列表框 JButtonjbExtract;//解压按钮 ZipFilezFile; publicZipExtractDemo(){ super("从压缩包中提取文件");//调用父类构造函数 fileChooser=newJFileChooser();//实例化组件 jtfTarget=newJTextField(13); jbSelected=newJButton("选择"); jbExtract=newJButton("解压"); files=newJList(); JPanelpanel=newJPanel();//实例化面板 panel.add(newJLabel("目标文件")); panel.add(jtfTarget);//增加组件到面板上 panel.add(jbSelected); panel.add(jbExtract); JScrollPanejsp=newJScrollPane(files); jsp.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));//设置边界 Containercontainer=getContentPane();//得以容器 container.add(panel,BorderLayout.NORTH);//增加组件到容器上 container.add(jsp,BorderLayout.CENTER); jbSelected.addActionListener(newActionListener(){//文件选择按钮事件处理 publicvoidactionPerformed(ActionEventevent){ if(fileChooser.showOpenDialog(ZipExtractDemo.this)==JFileChooser.APPROVE_OPTION){//弹出文件选择器,并判断是否点击了打开按钮 StringfileName=fileChooser.getSelectedFile().getAbsolutePath();//得到选择文件的绝对路径 jtfTarget.setText(fileName);//设置目标文件名 showFiles();//显示压缩包内容 } } }); jbExtract.addActionListener(newActionListener(){//解村文件按钮事件处理 publicvoidactionPerformed(ActionEventevent){ extractFile(files.getSelectedValue().toString());//解压指定文件 } }); setSize(350,250);//设置窗口尺寸 setVisible(true);//设置窗口可视 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时退出程序 } publicvoidshowFiles(){ try{ zFile=newZipFile(jtfTarget.getText());//得到压缩文件实例 ZipEntryentry; Vectorvec=newVector();//文件枚举 Enumerationenu=zFile.entries();//得到压缩条目的枚举对象 while(enu.hasMoreElements()){//依次枚举条目 entry=(ZipEntry)enu.nextElement();//得到压缩条目 vec.add(entry.getName());//增加文件到Vector内 } files.setListData(vec);//设置文件列表框数据 files.getSelectedValues(); } catch(Exceptionex){ ex.printStackTrace();//输出错误信息 } } publicvoidextractFile(Stringname){//解压文件 try{ ZipEntryentry=zFile.getEntry(name); entry.getComment(); entry.getCompressedSize(); entry.getCrc(); entry.isDirectory(); entry.getSize(); entry.getMethod(); InputStreamin=zFile.getInputStream(entry);//得到文件输入流 Filefile=newFile(name);//实例化文件对象 FileOutputStreamout=newFileOutputStream(file);//得到文件输出流 byte[]buffer=newbyte[1024];//缓冲区大小 intlength; while((length=in.read(buffer))!=-1){//循环读取数据 out.write(buffer,0,length);//写数据到输出流 } JOptionPane.showMessageDialog(ZipExtractDemo.this,"解压成功,解压到:"+file.getAbsolutePath()); in.close();//关闭输入流 out.close();//关闭输出流 }catch(Exceptionex){} } publicstaticvoidmain(String[]args){ newZipExtractDemo(); } }
总结
以上所述是小编给大家介绍的Java压缩/解压文件的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!