我想压缩一个包含文件和子目录的目录。我这样做了并且工作得很好,但是我得到了不寻常且好奇的文件结构(至少我是这样认为的)。
这是创建的文件:当我单击它时,我看到一个“空”目录,如下所示:但是当我解压缩它时,我看到这个文件结构(并非所有名称都完全如下图所示):
|mantenimiento
|Carpeta_A
|File1.txt
|File2.txt
|Carpeta_B
|Sub_carpetaB
|SubfileB.txt
|Subfile1B.txt
|Subfile2B.txt
|File12.txt
我的问题是,文件夹“mantenimiento”是我压缩的位置(我想要压缩的目录),但我不希望它在那里,所以当我解压缩刚刚创建的.zip文件时,我希望它具有以下文件结构(即“mantenimiento”目录内的文件和目录): 另一件事是,当我单击 .zip 文件时,我想看到文件和目录,就像上面显示的图像一样。
我不知道我的代码出了什么问题,我已经搜索过,但没有找到有关我的问题可能是什么的引用。
这是我的代码:
private void zipFiles( List<File> files, String directory) throws IOException
{
ZipOutputStream zos = null;
ZipEntry zipEntry = null;
FileInputStream fin = null;
FileOutputStream fos = null;
BufferedInputStream in = null;
String zipFileName = getZipFileName();
try
{
fos = new FileOutputStream( File.separatorChar + zipFileName + EXTENSION );
zos = new ZipOutputStream(fos);
byte[] buf = new byte[1024];
int len;
for(File file : files)
{
zipEntry = new ZipEntry(file.toString());
fin = new FileInputStream(file);
in = new BufferedInputStream(fin);
zos.putNextEntry(zipEntry);
while ((len = in.read(buf)) >= 0)
{
zos.write(buf, 0, len);
}
}
}
catch(Exception e)
{
System.err.println("No fue posible zipear los archivos");
e.printStackTrace();
}
finally
{
in.close();
zos.closeEntry();
zos.close();
}
}
希望你们能给我一些提示,告诉我我做错了什么或者我错过了什么。
非常感谢。
顺便说一句,我提供给该方法的目录从未被使用过。我给出的另一个参数是一个文件列表,其中包含 C:\mantenimiento 目录中的所有文件和目录。
最佳答案
我曾经遇到过 Windows 和 zip 文件的问题,其中创建的 zip 不包含文件夹条目(即 /
、/Carpeta_A
等),仅包含文件条目。尝试为没有流内容的文件夹添加 ZipEntries。
但是,作为 Java 有点笨重的 Zip API 的替代方案,您可以使用文件系统(自 Java7 起)。以下示例适用于 Java8 (lambda):
//Path pathToZip = Paths.get("path/to/your/folder");
//Path zipFile = Paths.get("file.zip");
public Path zipPath(Path pathToZip, Path zipFile) {
Map<String, String> env = new HashMap<String, String>() {{
put("create", "true");
}};
try (FileSystem zipFs = FileSystems.newFileSystem(URI.create("jar:" + zipFile.toUri()), env)) {
Path root = zipFs.getPath("/");
Files.walk(pathToZip).forEach(path -> zip(root, path));
}
}
private static void zip(final Path zipRoot, final Path currentPath) {
Path entryPath = zipRoot.resolve(currentPath.toString());
try {
Files.createDirectories(entryPath.getParent());
Files.copy(currentPath, entryPath);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
关于java - 使用 Java 压缩目录时出现奇怪的结构文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36855330/