我已经编程Java大约15年了。虽然这是一个基本问题,但这并不是因为故意无知Java API或阅读文档。坦率地说,我真的感到震惊,因为我遇到了我无法使用命令行工具创建一个简单的jar文件并使用java.util.jar.*
API打开它。我的详细步骤-step流程如下。
我使用jar -cf
创建了一个简单的.jar
文件进行测试。它包含一个文本文件。这是我的shell的输出,显示我是如何在我的Maven项目的src/test/resources
目录中创建的:
Laird-Nelsons-MacBook-Pro:resources ljnelson$ cat > a.txt
Hello!
Laird-Nelsons-MacBook-Pro:resources ljnelson$ jar cf source.jar .
Picked up _JAVA_OPTIONS: -Dfile.encoding=UTF-8
Laird-Nelsons-MacBook-Pro:resources ljnelson$ ls -al
total 16
drwxr-xr-x 4 ljnelson staff 136 Dec 28 13:21 .
drwxr-xr-x 4 ljnelson staff 136 Dec 28 13:01 ..
-rw-r--r-- 1 ljnelson staff 7 Dec 28 13:21 a.txt
-rw-r--r-- 1 ljnelson staff 445 Dec 28 13:21 source.jar
Laird-Nelsons-MacBook-Pro:resources ljnelson$ jar tf source.jar
Picked up _JAVA_OPTIONS: -Dfile.encoding=UTF-8
META-INF/
META-INF/MANIFEST.MF
a.txt
(Picked up _JAVA_OPTIONS: -Dfile.encoding=UTF-8
是解决Mac错误,其中终端上的默认文件编码为MacRoman
。如果您愿意,您需要手动将文件编码设置为UTF-8
在屏幕上看到准确表示的Unicode字符。据我所知,这与我看到的问题无关。)
然后,在创建JarFile
时,以下测试用例代码失败:
public File getSourceJarFile() throws IOException, URISyntaxException {
final URL url = this.getClass().getResource("/source.jar");
assertNotNull(url);
final URI uri = url.toURI();
assertNotNull(uri);
final String path = uri.getPath();
assertNotNull(path);
return new File(path);
}
@Test
public void testWTF() throws IOException, URISyntaxException {
final File file = this.getSourceJarFile();
assertNotNull(file);
assertTrue(file.isFile());
assertTrue(file.canRead());
// At this point, the file itself is there and can be read by this user.
JarFile jarFile = null;
try {
jarFile = new JarFile(file); // XXX KABOOM
} finally {
if (jarFile != null) {
jarFile.close();
}
}
}
例外是:
java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:127)
at java.util.jar.JarFile.<init>(JarFile.java:135)
at java.util.jar.JarFile.<init>(JarFile.java:99)
at com.foobar.TestCaseJarFileWTF.testWTF(TestCaseJarFileWTF.java:72)
回顾一下:
source.jar
命令行工具的最简单调用,在我的测试用例可访问的位置创建了一个jar
文件。emacs
,jar -xf
和unzip
成功打开此文件。它是一个有效的jar和zip文件。我觉得很愚蠢承认这一点,但我想我对JarFile
构造函数的工作方式一定没有最基本的理解。这里的任何输入都非常感谢。
答案 0 :(得分:1)
Maven再次罢工。我为Maven filtering设置了测试资源区域,因此生成的zip文件可能已经内部加密了。我希望我在这里的失败能帮助其他人解决类似问题。