Dot Net下解壓一個文件很簡單:
ZipFile.ExtractToDirectory("test.zip", "./test");
但是一個程序在Mac下運行Dot Net程序去解壓一個zip文件,目錄結構都沒有了,如下圖:
image.png
研究了一下,發現原因是生成這個zip是用的Java的java.util.zip寫的壓縮方法生成的,壓縮目錄是用
File.separator
來拼接目錄名,而程序又是在Windows下運行的,導致用的是\
符號到mac或linux下解壓不識別這個符號,把目錄標識當成文件名的一個字符。
解決的方法很簡單,把File.separator
直接改成/
就可以了。順便試了一下用Windows操作系統帶的壓縮工具和7zip壓縮出來的zip在Mac下解壓不會有這個問題。
最后附上Java修改后的壓縮代碼:
public ZipCompressor(File i, File o) {
source = i;
if (!source.exists()) { throw new RuntimeException(i + " : has not been found"); }
target = o;
}
public void execute() {
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target));
compress(source, out, "");
out.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void compress(File file, ZipOutputStream out, String basedir) {
if (file.isDirectory()) {
this.compressD(file, out, basedir);
} else {
this.compressF(file, out, basedir);
}
}
private void compressD(File dir, ZipOutputStream out, String basedir) {
if (!dir.exists()) return;
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
compress(files[i], out, basedir + dir.getName() + "/");
}
}
private void compressF(File file, ZipOutputStream out, String basedir) {
if (!file.exists()) { return; }
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(basedir + file.getName());
out.putNextEntry(entry);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}