一、题目描述-压缩文本文件
1、题目
题目:使用文本压缩技术,可以节约磁盘空间,还便于管理。
实现:做一个压缩指定文件夹内的所有文本文件的工具。
2、解题思路
创建一个类:ZipTextFileFrame
使用ZipTextFileFrame继承JFrame构建窗体
压缩文件主要用到压缩输出流ZipOutputStream
以zip文件格式写入文件实现输出流过滤器。
每一个文件在压缩过程中会被存到zipEntry
使用putNextEntry()方法,增加zipEntry
压缩文件会放在选择文件夹的同级目录,并以java.zip命名。
3、代码详解
package com.xiaoxuzhu; import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; /** * Description: * * @author xiaoxuzhu * @version 1.0 * ** 修改记录: * 修改后版本 修改人 修改日期 修改内容 * 2022/5/4.1 xiaoxuzhu 2022/5/4 Create ** @date 2022/5/4 */ public class ZipTextFileFrame extends JFrame { /** * */ private static final long serialVersionUID = -8885017327239429018L; private JPanel contentPane; private JTextField chooseTextField; private JTable table; private File[] textFiles; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ZipTextFileFrame frame = new ZipTextFileFrame(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ZipTextFileFrame() { setTitle("压缩所有文本文件"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); JPanel choosePanel = new JPanel(); contentPane.add(choosePanel, BorderLayout.NORTH); chooseTextField = new JTextField(); choosePanel.add(chooseTextField); chooseTextField.setColumns(18); JButton chooseButton = new JButton("选择文件夹"); chooseButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { do_chooseButton_actionPerformed(arg0); } }); choosePanel.add(chooseButton); JPanel buttonPanel = new JPanel(); contentPane.add(buttonPanel, BorderLayout.SOUTH); JButton zipButton = new JButton("开始压缩"); zipButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { do_zipButton_actionPerformed(arg0); } }); buttonPanel.add(zipButton); JScrollPane scrollPane = new JScrollPane(); contentPane.add(scrollPane, BorderLayout.CENTER); table = new JTable(); scrollPane.setViewportView(table); } protected void do_chooseButton_actionPerformed(ActionEvent arg0) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setMultiSelectionEnabled(false); int result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { File selectFile = fileChooser.getSelectedFile(); chooseTextField.setText(selectFile.getAbsolutePath()); textFiles = selectFile.listFiles(new FileFilter() { @Override public boolean accept(File file) { if (file.getPath().endsWith(".txt")) { return true; } return false; } }); DefaultTableModel model = (DefaultTableModel) table.getModel(); model.setColumnIdentifiers(new Object[] { "序号", "文件名" }); for (int i = 0; i < textFiles.length; i++) { model.addRow(new Object[] { i + 1, textFiles[i].getName() }); } table.setModel(model); } } protected void do_zipButton_actionPerformed(ActionEvent arg0) { if (chooseTextField.getText().length() == 0) { JOptionPane.showMessageDialog(this, "请选择要压缩的文件夹", "", JOptionPane.WARNING_MESSAGE); return; } String zipFilePath = new File(chooseTextField.getText()).getParent(); try { zipFile(textFiles, new File(zipFilePath + File.separator + "java.zip")); JOptionPane.showMessageDialog(this, "完成压缩"); } catch (IOException e) { e.printStackTrace(); } } private static void zipFile(File[] files, File targetZipFile) throws IOException { // 利用给定的targetZipFile对象创建文件输出流对象 FileOutputStream fos = new FileOutputStream(targetZipFile); ZipOutputStream zos = new ZipOutputStream(fos);// 利用文件输出流创建压缩输出流 byte[] buffer = new byte[1024];// 创建写入压缩文件的数组 for (File file : files) {// 遍历全部文件 ZipEntry entry = new ZipEntry(file.getName());// 利用每个文件的名字创建ZipEntry对象 FileInputStream fis = new FileInputStream(file);// 利用每个文件创建文件输入流对象 zos.putNextEntry(entry);// 在压缩文件中添加一个ZipEntry对象 int read = 0; while ((read = fis.read(buffer)) != -1) { zos.write(buffer, 0, read);// 将输入写入到压缩文件 } zos.closeEntry();// 关闭ZipEntry fis.close();// 释放资源 } zos.close(); fos.close(); } }
压缩成功:
查看压缩结果:
二、题目描述-压缩文件解压到指定文件夹
1、题目
题目:实现一个压缩文件解压到指定文件夹的工具
2、解题思路
创建一个类:UnZipTextFileFrame
先获取一个zip格式的压缩文件
再指定要解压缩存放的文件夹
使用JAVA自带的压缩工具包来实现解压缩功能
利用用户选择的ZIP文件创建ZipFile对象
遍历ZipFile对象的枚举变量, 获得ZipEntry对象
获得的ZipEntry对象的输入流,将输入流写入到本地文件,这样就达到了解压缩功能。
3、代码详解
package com.xiaoxuzhu; import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel; /** * Description: * * @author xiaoxuzhu * @version 1.0 * ** 修改记录: * 修改后版本 修改人 修改日期 修改内容 * 2022/5/4.1 xiaoxuzhu 2022/5/4 Create ** @date 2022/5/4 */ public class UnZipTextFileFrame extends JFrame { /** * */ private static final long serialVersionUID = -7525621255251725313L; private JPanel contentPane; private JTextField sourceTextField; private JTable table; private File zipFile; private JTextField targetTextField; private File targetFile; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UnZipTextFileFrame frame = new UnZipTextFileFrame(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public UnZipTextFileFrame() { setTitle("压缩文件解压到指定文件夹"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); JPanel choosePanel = new JPanel(); contentPane.add(choosePanel, BorderLayout.NORTH); sourceTextField = new JTextField(); choosePanel.add(sourceTextField); sourceTextField.setColumns(10); JButton sourceButton = new JButton("Zip文件"); sourceButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { do_sourceButton_actionPerformed(arg0); } }); choosePanel.add(sourceButton); targetTextField = new JTextField(); choosePanel.add(targetTextField); targetTextField.setColumns(10); JButton targetButton = new JButton("解压到"); targetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { do_targetButton_actionPerformed(arg0); } }); choosePanel.add(targetButton); JPanel buttonPanel = new JPanel(); contentPane.add(buttonPanel, BorderLayout.SOUTH); JButton unzipButton = new JButton("开始解压缩"); unzipButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { do_unzipButton_actionPerformed(arg0); } }); buttonPanel.add(unzipButton); JScrollPane scrollPane = new JScrollPane(); contentPane.add(scrollPane, BorderLayout.CENTER); table = new JTable(); scrollPane.setViewportView(table); } protected void do_sourceButton_actionPerformed(ActionEvent arg0) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileFilter(new FileNameExtensionFilter("文本文件", "zip")); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { zipFile = fileChooser.getSelectedFile(); sourceTextField.setText(zipFile.getAbsolutePath()); } } protected void do_targetButton_actionPerformed(ActionEvent arg0) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { targetFile = fileChooser.getSelectedFile(); targetTextField.setText(targetFile.getAbsolutePath()); } } @SuppressWarnings("rawtypes") protected void do_unzipButton_actionPerformed(ActionEvent arg0) { DefaultTableModel model = (DefaultTableModel) table.getModel();// 获得表格模型 model.setColumnIdentifiers(new Object[] { "序号", "文件名" });// 设置表头 int id = 1;// 声明序号变量 ZipFile zf = null; try { zf = new ZipFile(zipFile);// 利用用户选择的ZIP文件创建ZipFile对象 Enumeration e = zf.entries();// 创建枚举变量 while (e.hasMoreElements()) {// 遍历枚举变量 ZipEntry entry = (ZipEntry) e.nextElement();// 获得ZipEntry对象 if (!entry.getName().endsWith(".txt")) {// 如果不是文本文件就不进行解压缩 continue; } // 利用用户选择的文件夹和ZipEntry对象名称创建解压后的文件 File currentFile = new File(targetFile + File.separator + entry.getName()); FileOutputStream out = new FileOutputStream(currentFile); InputStream in = zf.getInputStream(entry);// 利用获得的ZipEntry对象的输入流 int buffer = 0; while ((buffer = in.read()) != -1) {// 将输入流写入到本地文件 out.write(buffer); } model.addRow(new Object[] { id++, currentFile.getName() });// 增加一行表格数据 in.close();// 释放资源 out.close(); } table.setModel(model);// 更新表格 JOptionPane.showMessageDialog(this, "解压缩完成");// 提示用户解压缩完成 } catch (ZipException e) {// 捕获异常 e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (zf != null) { try { zf.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
解压成功:
三、题目描述-压缩所有子文件夹
1、题目
题目:做一个压缩所有子文件夹的工具
2、解题思路
创建一个类:ZipDirectoryFrame
使用ZipDirectoryFrame继承JFrame构建窗体
压缩包含子文件夹的文件夹方案和压缩全是文件的文件夹类似,区别在如果找出包含子文件夹的文件夹所有文件。
并且构造ZipEntry时,不要有重名的情况。
可以用要压缩文件夹中所有文件的相对路径来做区分。
ZipEntry entry = new ZipEntry(string.substring(base.length() + 1, string.length()));// 利用要压缩文件的相对路径创建ZipEntry对象
压缩文件会放在选择文件夹的同级目录,并以选择文件夹的文件夹名+“.zip”命名。
3、代码详解
package com.xiaoxuzhu; import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; /** * Description: 压缩所有子文件夹 * * @author xiaoxuzhu * @version 1.0 * ** 修改记录: * 修改后版本 修改人 修改日期 修改内容 * 2022/5/4.1 xiaoxuzhu 2022/5/4 Create ** @date 2022/5/4 */ public class ZipDirectoryFrame extends JFrame { /** * */ private static final long serialVersionUID = -138842864977841594L; private JPanel contentPane; private JTextField chooseTextField; private JTable table; private File selectFile; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ZipDirectoryFrame frame = new ZipDirectoryFrame(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ZipDirectoryFrame() { setTitle("压缩所有子文件夹"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); JPanel choosePanel = new JPanel(); contentPane.add(choosePanel, BorderLayout.NORTH); chooseTextField = new JTextField(); choosePanel.add(chooseTextField); chooseTextField.setColumns(18); JButton chooseButton = new JButton("选择文件夹"); chooseButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { do_chooseButton_actionPerformed(arg0); } }); choosePanel.add(chooseButton); JPanel buttonPanel = new JPanel(); contentPane.add(buttonPanel, BorderLayout.SOUTH); JButton zipButton = new JButton("开始压缩"); zipButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { do_zipButton_actionPerformed(arg0); } }); buttonPanel.add(zipButton); JScrollPane scrollPane = new JScrollPane(); contentPane.add(scrollPane, BorderLayout.CENTER); table = new JTable(); scrollPane.setViewportView(table); } protected void do_chooseButton_actionPerformed(ActionEvent arg0) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setMultiSelectionEnabled(false); int result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { selectFile = fileChooser.getSelectedFile(); chooseTextField.setText(selectFile.getAbsolutePath()); } } protected void do_zipButton_actionPerformed(ActionEvent arg0) { Listpath = new ArrayList (); getPath(selectFile, path); DefaultTableModel model = (DefaultTableModel) table.getModel(); model.setColumnIdentifiers(new Object[] { "序号", "文件" }); int id = 1; for (String string : path) { model.addRow(new Object[] { id++, new File(string).getName() }); } String targetZipFilePath = selectFile.getParent() +File.separator + selectFile.getName() + ".zip"; try { zipFile(path, new File(targetZipFilePath), selectFile.getAbsolutePath()); JOptionPane.showMessageDialog(this, "文件夹压缩成功"); } catch (IOException e) { e.printStackTrace(); } } private static void getPath(File rootFile, List path) { File[] files = rootFile.listFiles(); for (File file : files) { if (file.isDirectory()) { getPath(file, path); } else { path.add(file.getAbsolutePath()); } } } private void zipFile(List path, File targetZipFile, String base) throws IOException { // 根据给定的targetZipFile创建文件输出流对象 FileOutputStream fos = new FileOutputStream(targetZipFile); ZipOutputStream zos = new ZipOutputStream(fos);// 利用文件输出流对象创建Zip输出流对象 byte[] buffer = new byte[1024]; for (String string : path) {// 遍历所有要压缩文件的路径 File currentFile = new File(string); ZipEntry entry = new ZipEntry(string.substring(base.length() + 1, string.length()));// 利用要压缩文件的相对路径创建ZipEntry对象 FileInputStream fis = new FileInputStream(currentFile); zos.putNextEntry(entry); int read = 0; while ((read = fis.read(buffer)) != -1) {// 将数据写入到Zip输出流中 zos.write(buffer, 0, read); } zos.closeEntry();// 关闭ZipEntry对象 fis.close(); } zos.close();// 释放资源 fos.close(); } }
选择文件夹
要压缩的文件夹是上面两个例子的文件夹
压缩成功:
压缩结果:
到此这篇关于Java压缩文件操作详解的文章就介绍到这了,更多相关Java压缩文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!