Poison

关于 Zip 文件中的资源查找问题

1
InputStream InputStream = loader.getResourceAsStream(ipDirInJar + File.separator + dexFileName);

以上代码同事反馈在本地运行时 inputStream 为 null,发现同事使用的 Windows 系统,初步怀疑为编码问题或路径分隔符问题,经过本地 debug,发现寻找 jar 包中的含有路径分隔符的文件时,最终调用了以下方法,在 Windows 系统上返回了 0:

1
2
3
/Library/Java/JavaVirtualMachines/openjdk-8.jdk/Contents/Home/src.zip!/java/util/zip/ZipFile.java:335

private static native long getEntry(long jzfile, byte[] name, boolean addSlash);

经过查询文档,原来 zip 文件里面的路径分隔符必须使用 /,而不能使用平台独立的文件系统路径分隔符,故调整为了 / 解决了该问题。

4.4.17.1 The name of the file, with optional relative path. The path stored MUST NOT contain a drive or device letter, or a leading slash. All slashes MUST be forward slashes ‘/‘ as opposed to backwards slashes ‘' for compatibility with Amiga and UNIX file systems etc. If input came from standard input, there is no file name field.

Reference

.ZIP File Format Specification
Zip file is created with windows path separator