如何在zip文件中使用相对路径?(很急,解决马上给分,在线等候)
下面的代码实现了对指定文件夹中所有文件的压缩。压缩后的zip包中文件路径用的是绝对路径,怎样改才能实现用相对路径存储?
package zip;
import java.util.zip.*;
import java.io.*;
public class Zip {
private String sourceFolderName = null;
public void doZip(String sourceFolderName, String targetFolderName) throws Exception {
this.sourceFolderName = sourceFolderName;
String targetFileName = targetFolderName + "\\" +
sourceFolderName.substring(sourceFolderName.lastIndexOf(
"\\") + 1) + ".zip";
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(targetFileName));
go(sourceFolderName, zos);
zos.close();
}
public void go(String sourceName, ZipOutputStream zos) throws Exception {
File file = new File(sourceName);
if (file.isDirectory()) {
System.out.println("directory:" + file.getPath());
String[] entries = file.list();
String relativePath = file.getPath().substring(sourceFolderName.length());
for (int i = 0; i < entries.length; i++) {
go(file.getPath() + "\\" + entries[i], zos);
}
return;
}
byte[] buffer = new byte[4096];
int bytes_read;
FileInputStream fis = new FileInputStream(file);
ZipEntry entry = new ZipEntry(sourceName);
zos.putNextEntry(entry);
while ((bytes_read = fis.read(buffer)) != -1) {
zos.write(buffer, 0, bytes_read);
}
System.out.println("file:" + file.getPath());
fis.close();
}
public static void main(String[] argv) throws Exception{
new Zip().doZip("c:\\downloads\\ggg","c:\\downloads");
}
}
这段代码执行以后ggg.zip中的文件路径是c:\downloads\ggg\...
而我想打开ggg.zip后直接就看到的是ggg目录下的内容。