首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在不包含文件路径的情况下使用Java压缩文件

如何在不包含文件路径的情况下使用Java压缩文件
EN

Stack Overflow用户
提问于 2010-06-11 05:15:36
回答 7查看 22.7K关注 0票数 20

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

我做了这个方法:

代码语言:javascript
复制
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;
  }  
 }

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

我不想要压缩包中每个文件的完整路径,我只需要文件名。

我该怎么做呢?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2010-06-11 06:40:04

这里:

代码语言:javascript
复制
// Add ZIP entry to output stream. 
out.putNextEntry(new ZipEntry(filename)); 

您将使用整个路径为该文件创建条目。如果您只使用名称(不包括路径),您将获得所需的内容:

代码语言:javascript
复制
// Add ZIP entry to output stream. 
File file = new File(filename); //"Users/you/image.jpg"
out.putNextEntry(new ZipEntry(file.getName())); //"image.jpg"
票数 33
EN

Stack Overflow用户

发布于 2010-06-11 05:26:33

您将使用文件的相对路径查找源数据,然后将条目设置为相同的内容。相反,您应该将源文件转换为File对象,然后使用

新建(putNextEntry ZipEntry(sourceFile.getName()

这将只给你路径的最后一部分(即实际的文件名)

票数 2
EN

Stack Overflow用户

发布于 2010-06-11 05:39:59

as Jason said,或者如果你想保留你的方法签名,像这样做:

代码语言:javascript
复制
out.putNextEntry(new ZipEntry(new File(filename).getName())); 

或者,使用apache commons/io中的FileNameUtils.getName

代码语言:javascript
复制
out.putNextEntry(new ZipEntry(FileNameUtils.getName(filename))); 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3018579

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档