我有一個Java程序,用於壓縮目錄中的所有文件和子目錄。它會創建一個絕對路徑的壓縮文件,例如c:\ dir1 \ dirzip \,但我希望它只創建具有de文件和子目錄的文件,而不是絕對路徑。 CAn anaybode請幫助我? 這是我的代碼:包含文件和子目錄的zip目錄,不包含Java中的絕對路徑
import java.io.*;
import java.util.zip.*;
public class zip {
public static void main(String argv[]) {
try {
ZipOutputStream zos =
new ZipOutputStream(new FileOutputStream(
"c:\\pruebazip\\dancedragons.zip"));
zipDir("c:\\pruebazip\\dancedragons\\", zos);
zos.close();
}
catch (Exception e) {
}
}
public static void zipDir(String dir2zip, ZipOutputStream zos) {
try {
File zipDir = new File(dir2zip);
// lista del contenido del directorio
String[] dirList = zipDir.list();
// System.out.println(dirList[1]);
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
System.out.println(dirList.length);
// recorro el directorio y añado los archivos al zip
for (int i = 0; i < dirList.length; i++) {
File f = new File(zipDir, dirList[i]);
if (f.isDirectory()) {
String filePath = f.getPath();
zipDir(filePath, zos);
System.out.println(filePath);
continue;
}
FileInputStream fis = new FileInputStream(f);
ZipEntry anEntry = new ZipEntry(f.getPath());
zos.putNextEntry(anEntry);
while ((bytesIn = fis.read(readBuffer)) != -1) {
zos.write(readBuffer, 0, bytesIn);
}
fis.close();
}
}
catch (Exception e) {
// handle exception
}
}
}
的可能重複的[java.util.zip - 重新創建目錄結構](http://stackoverflow.com/questions/1399126/java-util-zip-recreating-directory-structure ) – McDowell 2012-01-30 14:14:58