我的目标是获取一些.class的流并创建一个JAR。
问题是JAR创建了存储.classes但不能用作类路径(它只是找不到类)。 JAR没有损坏,如果我解压缩JAR,我可以使用.classes。 那么,如果这段代码有什么问题呢?
@Test
public void createJARTest() throws IOException
{
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final JarOutputStream jarOutputStream = new JarOutputStream( byteArrayOutputStream );
final String path = "/com/app/MyClass.class";
final JarEntry entry = new JarEntry( path );
jarOutputStream.putNextEntry( entry );
final BufferedInputStream in = new BufferedInputStream( this.getClass().getResourceAsStream(path) );
final byte[] buffer = new byte[1024];
int bytesRead = 0;
while ( (bytesRead = in.read( buffer )) != -1 )
{
jarOutputStream.write( buffer, 0, bytesRead );
}
in.close();
jarOutputStream.closeEntry();
jarOutputStream.close();
byteArrayOutputStream.writeTo( new FileOutputStream("/Downloads/classpath.jar") );
byteArrayOutputStream.close();
}
答案 0 :(得分:1)
我发现了问题:
JarOutputStream有三个未记录的怪癖:
所以,解决方案只是换了一行:
final JarEntry entry = new JarEntry( "com/app/MyClass.class" );