Zip file is created with windows path separator

北城余情 提交于 2020-03-21 02:08:32

问题


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);
   }
}

回答1:


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));

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

So, according to this

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));


来源:https://stackoverflow.com/questions/57248542/zip-file-is-created-with-windows-path-separator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!