Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i zip files in Java and not include files paths

Tags:

For example, I want to zip a file stored in /Users/me/Desktop/image.jpg

I made this method:

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;
  }  
 }

But when I extract the file, the unzipped files have the full path.

I don't want the full path of each file in the zip i only want the filename.

How can I made this?

like image 553
Ignacio Avatar asked Jun 10 '10 21:06

Ignacio


People also ask

Can zip files contain files and directories?

ZIP is an archive file format that supports lossless data compression. A ZIP file may contain one or more files or directories that may have been compressed.

How do I zip a directory in Java?

Zipping a directory is little tricky, first we need to get the files list as absolute path. Then process each one of them separately. We need to add a ZipEntry for each file and use FileInputStream to read the content of the source file to the ZipEntry corresponding to that file.


2 Answers

Here:

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

You're creating the entry for that file using the whole path. If you just use the name ( without the path ) you'll have what you need:

// Add ZIP entry to output stream. 
File file = new File(filename); //"Users/you/image.jpg"
out.putNextEntry(new ZipEntry(file.getName())); //"image.jpg"
like image 158
OscarRyz Avatar answered Sep 17 '22 09:09

OscarRyz


You're finding your source data using the relative path to the file, then setting the Entry to the same thing. Instead you should turn the source into a File object, and then use

putNextEntry(new ZipEntry(sourceFile.getName()))

that'll give you just the final part of the path (ie, the actual file name)

like image 29
Jason Avatar answered Sep 18 '22 09:09

Jason