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

伊格纳西奥(Ignacio):

例如,我要压缩存储在/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中每个文件的完整路径,而只想要文件名。

我该怎么做?

奥斯卡·雷兹(OscarRyz):

这里:

// 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"

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章