将文件夹中的所有文件添加到zip文件中

 
  1. import java.io.File;   
  2. import java.io.FileInputStream;   
  3. import java.io.FileOutputStream;   
  4. import java.io.IOException;   
  5. import java.io.InputStream;   
  6. import java.util.Enumeration;   
  7. import org.apache.tools.zip.ZipEntry;   
  8. import org.apache.tools.zip.ZipFile;   
  9. import org.apache.tools.zip.ZipOutputStream;   
  10.   
  11. public class CompressFile {   
  12.     private static CompressFile instance = new CompressFile();   
  13.        
  14.     private CompressFile() {   
  15.     }   
  16.        
  17.     public static CompressFile getInstance() {   
  18.         return instance;   
  19.     }   
  20.   
  21.     public synchronized void zip(String inputFilename, String zipFilename)   
  22.             throws IOException {   
  23.         zip(new File(inputFilename), zipFilename);   
  24.     }   
  25.        
  26.     public synchronized void zip(File inputFile, String zipFilename) throws IOException {   
  27.         ZipOutputStream out = new ZipOutputStream(new FileOutputStream(   
  28.                 zipFilename));   
  29.   
  30.         try {   
  31.             zip(inputFile, out, "");   
  32.         } catch (IOException e) {   
  33.             throw e;   
  34.         } finally {   
  35.             out.close();   
  36.         }   
  37.     }   
  38.   
  39.     private synchronized void zip(File inputFile, ZipOutputStream out, String base)   
  40.             throws IOException {   
  41.         if (inputFile.isDirectory()) {   
  42.             File[] inputFiles = inputFile.listFiles();   
  43.             out.putNextEntry(new ZipEntry(base + "/"));   
  44.             base = base.length() == 0 ? "" : base + "/";   
  45.             for (int i = 0; i < inputFiles.length; i++) {   
  46.                 zip(inputFiles[i], out, base + inputFiles[i].getName());   
  47.             }   
  48.   
  49.         } else {   
  50.             if (base.length() > 0) {   
  51.                 out.putNextEntry(new ZipEntry(base));   
  52.             } else {   
  53.                 out.putNextEntry(new ZipEntry(inputFile.getName()));   
  54.             }   
  55.   
  56.             FileInputStream in = new FileInputStream(inputFile);   
  57.             try {   
  58.                 int c;   
  59.                 byte[] by = new byte[BUFFEREDSIZE];   
  60.                 while ((c = in.read(by)) != -1) {   
  61.                     out.write(by, 0, c);   
  62.                 }   
  63.             } catch (IOException e) {   
  64.                 throw e;   
  65.             } finally {   
  66.                 in.close();   
  67.             }   
  68.         }   
  69.     }   
  70.   
  71.     public synchronized void unzip(String zipFilename, String outputDirectory)   
  72.             throws IOException {   
  73.         File outFile = new File(outputDirectory);   
  74.         if (!outFile.exists()) {   
  75.             outFile.mkdirs();   
  76.         }   
  77.   
  78.         ZipFile zipFile = new ZipFile(zipFilename);   
  79.         Enumeration en = zipFile.getEntries();   
  80.         ZipEntry zipEntry = null;   
  81.         while (en.hasMoreElements()) {   
  82.             zipEntry = (ZipEntry) en.nextElement();   
  83.             if (zipEntry.isDirectory()) {   
  84.                 // mkdir directory   
  85.                 String dirName = zipEntry.getName();   
  86.                 dirName = dirName.substring(0, dirName.length() - 1);   
  87.   
  88.                 File f = new File(outFile.getPath() + File.separator + dirName);   
  89.                 f.mkdirs();   
  90.   
  91.             } else {   
  92.                 // unzip file   
  93.                 File f = new File(outFile.getPath() + File.separator   
  94.                         + zipEntry.getName());   
  95.                 f.createNewFile();   
  96.                 InputStream in = zipFile.getInputStream(zipEntry);   
  97.                 FileOutputStream out = new FileOutputStream(f);   
  98.                 try {   
  99.                     int c;   
  100.                     byte[] by = new byte[BUFFEREDSIZE];   
  101.                     while ((c = in.read(by)) != -1) {   
  102.                         out.write(by, 0, c);   
  103.                     }   
  104.                     // out.flush();   
  105.                 } catch (IOException e) {   
  106.                     throw e;   
  107.                 } finally {   
  108.                     out.close();   
  109.                     in.close();   
  110.                 }   
  111.             }   
  112.         }   
  113.     }   
  114.   
  115.     private static final int BUFFEREDSIZE = 1024;   
  116.        
  117.     public static void main(String[] args) {      
  118.         CompressFile bean = new CompressFile();      
  119.         try {      
  120.             bean.zip("d:/temp""d:/test.zip");      
  121.      
  122.             bean.unzip("d:/test.zip""d:/out/temp");      
  123.         } catch (IOException e) {      
  124.             e.printStackTrace();      
  125.         }      
  126.     }    
  127. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.cliff.common; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; import org.apache.tools.zip.ZipOutputStream; /** * * 类名: ZipUtil.java * 描述:压缩/解压缩zip包处理类 * 创建者:XXX * 创建日期:2015年5月7日 - 下午1:35:02 * 版本: V0.1 * 修改者: * 修改日期: */ public class ZipUtil { /** * * 功能描述:压缩文件 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:35:18 * 版本: V0.1 * 修改者: * 修改日期: * @param directory 指定压缩文件路径 压缩到同目录 * @throws IOException * void */ public static void zip(String directory) throws FileNotFoundException, IOException { zip("", null, directory); } /** * * 功能描述:压缩文件 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:36:03 * 版本: V0.1 * 修改者: * 修改日期: * @param zipFileName 压缩产生的zip文件名--带路径,如果为null或空则默认按文件名生产压缩文件名 * @param relativePath 相对路径,默认为空 * @param directory 文件或目录的绝对路径 * void */ public static void zip(String zipFileName, String relativePath, String directory) throws FileNotFoundException, IOException { String fileName = zipFileName; if (fileName == null || fileName.trim().equals("")) { File temp = new File(directory); if (temp.isDirectory()) { fileName = directory + ".zip"; } else { if (directory.indexOf(".") > 0) { fileName = directory.substring(0, directory.lastIndexOf("."))+ "zip"; } else { fileName = directory + ".zip"; } } } ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName)); try { zip(zos, relativePath, directory); } catch (IOException ex) { throw ex; } finally { if (null != zos) { zos.close(); } } } /** * * 功能描述:压缩文件 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:37:55 * 版本: V0.1 * 修改者: * 修改日期: * @param zos 压缩输出流 * @param relativePath 相对路径 * @param absolutPath 文件文件夹绝对路径 * @throws IOException * void */ private static void zip(ZipOutputStream zos, String relativePath, String absolutPath) throws IOException { File file = new File(absolutPath); if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { File tempFile = files[i]; if (tempFile.isDirectory()) { String newRelativePath = relativePath + tempFile.getName() + File.separator; createZipNode(zos, newRelativePath); zip(zos, newRelativePath, tempFile.getPath()); } else { zipFile(zos, tempFile, relativePath); } } } else { zipFile(zos, file, relativePath); } } /** * * 功能描述:压缩文件 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:38:46 * 版本: V0.1 * 修改者: * 修改日期: * @param zos 压缩输出流 * @param file 文件对象 * @param relativePath 相对路径 * @throws IOException * void */ private static void zipFile(ZipOutputStream zos, File file, String relativePath) throws IOException { ZipEntry entry = new ZipEntry(relativePath + file.getName()); zos.putNextEntry(entry); InputStream is = null; try { is = new FileInputStream(file); int BUFFERSIZE = 2 <= 0) { zos.write(buffer, 0, length); } zos.flush(); zos.closeEntry(); } catch (IOException ex) { throw ex; } finally { if (null != is) { is.close(); } } } /** * * 功能描述:创建目录 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:39:12 * 版本: V0.1 * 修改者: * 修改日期: * @param zos zip输出流 * @param relativePath 相对路径 * @throws IOException * void */ private static void createZipNode(ZipOutputStream zos, String relativePath) throws IOException { ZipEntry zipEntry = new ZipEntry(relativePath); zos.putNextEntry(zipEntry); zos.closeEntry(); } /** * * 功能描述:解压缩文件 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:39:32 * 版本: V0.1 * 修改者: * 修改日期: * @param zipFilePath zip文件路径 * @param targetPath 解压缩到的位置,如果为null或空字符串则默认解压缩到跟zip包同目录跟zip包同名的文件夹下 * void */ public static void unzip(String zipFilePath, String targetPath) throws IOException { InputStream is = null; FileOutputStream fileOut = null; File file = null; ZipFile zipFile = null; try { zipFile = new ZipFile(zipFilePath,"GBK"); String directoryPath = ""; if (null == targetPath || "".equals(targetPath)) { directoryPath = zipFilePath.substring(0, zipFilePath.lastIndexOf(".")); } else { directoryPath = targetPath; } for(Enumeration entries = zipFile.getEntries(); entries.hasMoreElements();){ ZipEntry entry = (ZipEntry)entries.nextElement(); file = new File(directoryPath+"/"+entry.getName()); if(entry.isDirectory()){ file.mkdirs(); }else{ //如果指定文件的目录不存在,则创建之. File parent = file.getParentFile(); if(!parent.exists()){ parent.mkdirs(); } is = zipFile.getInputStream(entry); fileOut = new FileOutputStream(file); int readLen = 0; byte[] buffer = new byte[4096]; while ((readLen = is.read(buffer, 0, 4096)) >= 0) { fileOut.write(buffer, 0, readLen); } fileOut.close(); is.close(); } } zipFile.close(); } catch (IOException ex) { throw ex; } finally { if(null != zipFile){ zipFile = null; } if (null != is) { is.close(); } if (null != fileOut) { fileOut.close(); } } } /** * * 功能描述:生产文件 如果文件所在路径不存在则生成路径 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:41:04 * 版本: V0.1 * 修改者: * 修改日期: * @param fileName 文件名 带路径 * @param isDirectory 是否为路径 * @return * File */ public static File buildFile(String fileName, boolean isDirectory) { File target = new File(fileName); if (isDirectory){ target.mkdirs(); } else { if (!target.getParentFile().exists()) { target.getParentFile().mkdirs(); target = new File(target.getAbsolutePath()); } } return target; } }
### 回答1: 在 Python ,你可以使用 `zipfile` 模块来将一个文件夹备份到一个 ZIP 文件。 下面是一个示例代码: ``` import os import zipfile def backup_to_zip(folder): # 将文件夹名称作为 ZIP 文件名 folder = os.path.abspath(folder) number = 1 while True: zip_filename = f'{folder}_backup{number}.zip' if not os.path.exists(zip_filename): break number += 1 # 创建 ZIP 文件 print(f'Creating {zip_filename}...') backup_zip = zipfile.ZipFile(zip_filename, 'w') # 遍历文件夹树,将文件加入 ZIP 文件 for foldername, subfolders, filenames in os.walk(folder): print(f'Adding files in {foldername}...') backup_zip.write(foldername) # 将文件加入 ZIP 文件 for filename in filenames: new_base = os.path.basename(folder) + '_' if filename.startswith(new_base) and filename.endswith('.zip'): continue # 不要将备份文件夹备份到 ZIP 文件 backup_zip.write(os.path.join(foldername, filename)) backup_zip.close() print('Done.') backup_to_zip('example') # 将 example 文件夹备份到 ZIP 文件 ``` 在这段代码,我们首先使用 `os.path.abspath()` 函数获取文件夹的绝对路径,然后使用 `while` 循环生成一个新的 ZIP 文件名。接下来,我们使用 `zipfile.ZipFile()` 函数创建一个新的 ZIP 文件,并使用 `os.walk()` 函数遍历文件夹树。对于每个文件夹,我们使用 `zipfile.write()` 函数将其加入 ZIP 文件,然后遍历该文件夹文件,并将这些 ### 回答2: 要将一个文件夹备份到一个ZIP文件,可以使用Pythonzipfile模块。下面是一个实现这个功能的简单代码: ```python import zipfile import os def backup_to_zip(folder): # 获取文件夹的绝对路径 folder = os.path.abspath(folder) # 检查备份文件文件zip_file_name = os.path.basename(folder) + '.zip' # 创建一个ZipFile对象,打开zip文件以写入模式 backup_zip = zipfile.ZipFile(zip_file_name, 'w') # 遍历文件夹的所有子文件和子文件夹 for foldername, subfolders, filenames in os.walk(folder): # 将文件夹添加ZIP文件 backup_zip.write(foldername) # 将文件夹的所有文件添加ZIP文件 for filename in filenames: file_path = os.path.join(foldername, filename) backup_zip.write(file_path) # 关闭ZipFile对象 backup_zip.close() print(f'成功将文件夹备份到 {zip_file_name} 文件。') # 示例调用 backup_folder = '/path/to/your/folder' backup_to_zip(backup_folder) ``` 以上代码首先需要导入zipfile模块和os模块。然后定义了一个名为backup_to_zip的函数,参数为要备份的文件夹路径。函数使用os模块的abspath函数获取文件夹的绝对路径,并使用os模块的basename函数获取备份文件文件名。 然后,创建一个ZipFile对象,以写入模式打开要生成ZIP文件。接下来,使用os模块的walk函数遍历文件夹的所有子文件和子文件夹,通过write方法将它们逐个添加ZIP文件。 最后,关闭ZipFile对象,并在控制台打印出备份操作成功的消息。 你只需将`/path/to/your/folder`替换为你要备份的文件夹的实际路径,运行代码即可将文件夹备份为一个ZIP文件。 ### 回答3: 使用Python可以使用zipfile模块来备份一个文件夹到一个ZIP文件。下面是一个简单的示例代码: ```python import zipfile import os def backup_folder_to_zip(folder_path, zip_path): with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: for root, dirs, files in os.walk(folder_path): for file_name in files: file_path = os.path.join(root, file_name) zipf.write(file_path, os.path.relpath(file_path, folder_path)) if __name__ == '__main__': folder_path = '/path/to/folder' # 文件夹路径 zip_path = '/path/to/backup.zip' # ZIP文件路径 backup_folder_to_zip(folder_path, zip_path) ``` 在这个例子,我们定义了一个名为backup_folder_to_zip的函数,它接受文件夹路径和ZIP文件路径作为参数。然后,我们使用zipfile.ZipFile来创建一个新的ZIP文件,并使用ZIP_DEFLATED参数指定压缩模式。 接下来,我们使用os.walk函数遍历文件夹的所有文件和子文件夹。对于每个文件,我们使用zipf.write将其添加ZIP文件。os.path.relpath函数用于获取文件相对于文件夹的相对路径,以便在ZIP文件保持文件文件夹结构。 最后,在主程序,我们提供了文件夹路径和ZIP文件路径,并调用backup_folder_to_zip函数来完成备份过程。 值得注意的是,这只是一个简单的示例代码,你还可以根据你的需求行更多的定制和错误处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值