Repacking jar files: solution

S

Simon Brooke

A few days ago I posted to this group under the subject 'Repacking jar
files'. In brief, my problem was that although I could programatically
create a file which appeared to be a jar file, neither the jar utility
nor WinZip could unpack it (although some other zip tools could).
Having found the solution, I'm posting this for the benefit of the poor
benighted soul who is to come after me...

The 'D'oh!' moment came as I was sleeping. I woke up at an ungodly hour
this morning with the fixed message 'don't write the dirs' imprinted on
my brain, so I shambled out of bed in a daze, dragged some clothes on,
sat down at my desk and tried it.

Hai! Karamba! It works!

I had been doing
Stack toWrite = new Stack( );

toWrite.push( dir );

while ( !toWrite.empty( ) )
{
File current = (File) toWrite.pop( );

jout.putNextEntry( new JarEntry( getRelativePath( current, dir ) ) );

if ( current.isDirectory( ) )
{
/** push all my files and subdirs onto the stack */
String[] children = current.list( );

for ( int child = 0; child < children.length; child++ )
{
toWrite.push( new File( current, children[child] ) );
}
}
else
{
/** write contents of file to stream */
InputStream in =
new BufferedInputStream( new FileInputStream( current ) );

for ( int i = in.read( ); i > -1; i = in.read( ) )
jout.write( i );
}
}

Don't do this at home, kids, it's wrong. Being warned in a dream, I
went home by a different route, namely

Stack toWrite = new Stack( );

toWrite.push( dir );

while ( !toWrite.empty( ) )
{
File current = (File) toWrite.pop( );

if ( current.isDirectory( ) )
{
/** push all my files and subdirs onto the stack */
String[] children = current.list( );

for ( int child = 0; child < children.length; child++ )
{
toWrite.push( new File( current, children[child] ) );
}
}
else
{
JarEntry entry = new JarEntry( getRelativePath( current, dir ) );

entry.setSize( current.length());

jout.putNextEntry( entry );

/** write contents of file to stream */
InputStream in =
new BufferedInputStream( new FileInputStream( current ) );

for ( int i = in.read( ); i > -1; i = in.read( ) )
jout.write( i );
}
}

In short, you create JarEntry objects only for plain files, not for
directories - the directories are implied.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top