当前位置: 首页 > 面试题库 >

如何在Java中压缩文件而不包含文件路径

梁修贤
2023-03-14
问题内容

例如,我要压缩存储在/Users/me/Desktop/image.jpg中的文件

我做了这个方法:

public static Boolean generateZipFile(ArrayList<String> sourcesFilenames, String destinationDir, String zipFilename){
  // Create a buffer for reading the files 
  byte[] buf = new byte[1024];

  try {
   // VER SI HAY QUE CREAR EL ROOT PATH
         boolean result = (new File(destinationDir)).mkdirs();

         String zipFullFilename = destinationDir + "/" + zipFilename ;

         System.out.println(result);

   // Create the ZIP file  
   ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFullFilename)); 
   // Compress the files 
   for (String filename: sourcesFilenames) { 
    FileInputStream in = new FileInputStream(filename); 
    // Add ZIP entry to output stream. 
    out.putNextEntry(new ZipEntry(filename)); 
    // Transfer bytes from the file to the ZIP file 
    int len; 
    while ((len = in.read(buf)) > 0) { 
     out.write(buf, 0, len); 
    } 
    // Complete the entry 
    out.closeEntry(); 
    in.close(); 
   } // Complete the ZIP file 
   out.close();

   return true;
  } catch (IOException e) { 
   return false;
  }  
 }

但是,当我提取文件时,解压缩的文件具有完整路径。

我不希望zip中每个文件的完整路径,而只想要文件名。

我该怎么做?


问题答案:

这里:

// Add ZIP entry to output stream. 
out.putNextEntry(new ZipEntry(filename));

您正在使用整个路径为该文件创建条目。如果仅使用名称(不带路径),则将具有所需的内容:

// Add ZIP entry to output stream. 
File file = new File(filename); //"Users/you/image.jpg"
out.putNextEntry(new ZipEntry(file.getName())); //"image.jpg"


 类似资料:
  • 问题内容: 任何人都可以向我展示在我一直在搜索的Java中压缩和解压缩tar.gzip文件的正确方法,但是我能找到的最多是zip或gzip(单独)。 问题答案: 我最喜欢的是plexus-archiver-请参阅GitHub上的资源。 另一个选项是Apache commons- compress- (请参阅mvnrepository)。 使用plexus-utils,用于取消存档的代码如下所示:

  • 问题内容: 我正在尝试压缩包含子文件夹的文件夹。尝试压缩名为10-18-2010_4D的文件夹。以上程序以以下异常结束。请提供有关如何解决此问题的建议。 问题答案: 您需要检查文件是否为目录,因为您无法将目录传递给zip方法。 看一下该页面,该页面显示了如何递归压缩给定目录。

  • 我正在使用Julia的ZipFile包来提取和处理csv文件。没问题,但是当我遇到zip文件中的zip文件时,我也想处理它,但是遇到了一个错误。 Julia ZipFile文档如下:https://zipfilejl.readthedocs.io/en/latest/ 对如何做到这一点有什么想法吗?

  • 问题内容: 我的应用程序正在通过SMTP服务器接收电子邮件。电子邮件中有一个或多个附件,电子邮件附件以byte []的形式返回(使用sun javamail api)。 我正在尝试快速压缩附件文件,而不先将其写入磁盘。 有什么/可能的方法来实现这一结果? 问题答案: 您可以使用Java的java.util.zip.ZipOutputStream在内存中创建一个zip文件。例如:

  • 问题内容: 我已经使用follwoing命令打包了我的电子应用程序 现在,我需要将其解压缩并重新获得整个代码。反正有这样做吗? 问题答案: 从asar文档 (此处的用法是避免使用全局安装该工具) 提取整个档案: 提取特定文件:

  • 我有一个JSON文件,它是。 我可以使用下载压缩文件。