[英]zip directory with files and subdirectories without the absolute path in Java
I have a program in Java that zip all the files and subdirectories of a directory. 我有一个用Java压缩一个目录的所有文件和子目录的程序。 It creates a zip file with the absolute path, for example c:\\dir1\\dirzip\\, but I want that it creates the file with only de files and subdirectories, not the absolute path.
它使用绝对路径创建一个zip文件,例如c:\\ dir1 \\ dirzip \\,但是我希望它仅使用de文件和子目录创建文件,而不使用绝对路径。 CAn anaybode help me , please??
可以让我帮忙吗? This is my code:
这是我的代码:
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
}
}
}
If you'd like for each zip entry to be stored in the directory structure relative to the zipped folder, then instead of constructing the ZipEntry with the files full path: 如果您希望将每个zip条目存储在相对于zipped文件夹的目录结构中,则不要使用文件完整路径构造ZipEntry:
new ZipEntry(f.getPath());
Construct it with its path relative to the zipped directory: 使用相对于压缩目录的路径构造它:
String relativePath = zipDir.toURI().relativize(f.toURI()).getPath();
new ZipEntry(relativePath);
Your issue may be the statement 您的问题可能是声明
new ZipEntry(f.getPath())
Double-check that f.getPath() is not an absolute path like C:\\dir\\...
. 仔细检查f.getPath()不是像
C:\\dir\\...
这样的绝对路径。
You may want something like new ZipEntry(dirList[i])
instead. 您可能需要像
new ZipEntry(dirList[i])
这样的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.