Create Zip File In Windows and Extract Zip File In Linux
- by Yan Cheng CHEOK
I had created a zip file (together with directory) under Windows as follow :
package sandbox;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
*
* @author yan-cheng.cheok
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// These are the files to include in the ZIP file
String[] filenames = new String[]{"MyDirectory" + File.separator + "MyFile.txt"};
// Create a buffer for reading the files
byte[] buf = new byte[1024];
try {
// Create the ZIP file
String outFilename = "outfile.zip";
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
// Compress the files
for (int i=0; i<filenames.length; i++) {
FileInputStream in = new FileInputStream(filenames[i]);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(filenames[i]));
// 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();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The newly created zip file can be extracted without problem under Windows, by using http://www.exampledepot.com/egs/java.util.zip/GetZip.html
However, I realize if I extract the newly created zip file under Linux, using http://www.exampledepot.com/egs/java.util.zip/GetZip.html, I will get a file named
"MyDirectory\MyFile.txt" instead of MyFile.txt being placed under folder MyDirectory.
I try to solve the problem by changing the zip file creation code to
String[] filenames = new String[]{"MyDirectory" + "/" + "MyFile.txt"};
But, is this an eligible solution, by hard-coded the seperator? Will it work under Mac OS? (I do not have a Mac to try out)