使用Windows路径分隔符创建Zip文件 [英] Zip file is created with windows path separator

查看:61
本文介绍了使用Windows路径分隔符创建Zip文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码创建一个zip文件.正确创建了Zip,然后稍后在我的程序中,我尝试从该文件中获取Zip条目.而且,如果我打印一个zip条目名称,则会得到Windows路径分隔符(例如\a\b\c).但是我需要像a/b/c这样的东西.我尚未发布阅读邮政编码的邮政编码.

I create a zip file using below code. Zip is created properly, then later in my program I try to get a zip entry from this file. And if I print a zip entry name I get windows path separators(Eg \a\b\c). But I need this like a/b/c. I have not posted reading zip entry code.

public static void zipFolder(File subdirs, String ZipName) throws FileNotFoundException, IOException {

   try (FileOutputStream fileWriter = new FileOutputStream(location+File.seperator+ ZipName); 
        ZipOutputStream zip = new ZipOutputStream(fileWriter)) {
            addFolderToZip(subdirs, subdirs, zip);
   }
}

private static void addFileToZip(File rootPath, File srcFile, ZipOutputStream zip) throws FileNotFoundException, IOException {

   if (srcFile.isDirectory()) {
      addFolderToZip(rootPath, srcFile, zip);
   } else {
      byte[] buf = new byte[1024];
      int len;
      try (FileInputStream in = new FileInputStream(srcFile)) {
         String name = srcFile.getPath();
         name = name.replace(rootPath.getPath() + File.separator, "");
         zip.putNextEntry(new ZipEntry(name));
         while ((len = in.read(buf)) > 0) {
                    zip.write(buf, 0, len);
         }
      }
   }
}

private static void addFolderToZip(File rootPath, File srcFolder, ZipOutputStream zip) throws FileNotFoundException, IOException {
   for (File fileName : srcFolder.listFiles()) {
     addFileToZip(rootPath, fileName, zip);
   }
}

推荐答案

以下代码段中导致问题的根本原因:

The root cause of your problem in the following snippet:

  String name = srcFile.getPath();
  name = name.replace(rootPath.getPath() + File.separator, "");
  zip.putNextEntry(new ZipEntry(name));

File.getPath( )方法返回带有系统依赖的默认名称分隔符的路径.

The File.getPath() method returns the path with the system-dependent default name-separator.

因此,根据

在ZIP文件中,路径名使用 ZIP规范(4.4.17.1).这需要在Windows之类的系统上与本地file.separator进行转换. API(ZipEntry)不会处理转换,也没有记录程序员处理它的需要.

Within a ZIP file, pathnames use the forward slash / as separator, as required by the ZIP spec (4.4.17.1). This requires a conversion from or to the local file.separator on systems like Windows. The API (ZipEntry) does not take care of the transformation, and the need for the programmer to deal with it is not documented.

您应通过以下方式重写此代码段:

you should rewrite this snippet in the following way:

  String name = srcFile.getPath();
  name = name.replace(rootPath.getPath() + File.separator, "");
  if (File.separatorChar != '/') {
     name = name.replace('\\', '/');
  }
  zip.putNextEntry(new ZipEntry(name));

这篇关于使用Windows路径分隔符创建Zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆