Thomas Okken wrote:
>
> Hi all,
>
> I'm working on something that requires a static array of almost 400k.
> I figured that the best way to initialize this array would be to
> compress the data, add a static array with an initializer to put the
> compressed data there (gzip compresses it to about 22k, which seems
> reasonable), and then add a static {} block that uses java.util.zip
> to decompress this data.
>
> Here's the code, edited for clarity:
>
> import java.util.zip.*;
>
> public class MyClass
> {
> ....
> }
>
> I'm having all sorts of problems with this. First of all, it just
> doesn't work. Inflater.inflate() throws a DataFormatException with
> message "invalid block type" (the initializer for myGzippedData was
> generated from a .gz file, and if I dump that data to System.out
> using write(), and pipe that to gunzip, it works fine).
> Also, the .class file is huge -- more than 330k. I would expect an
> initializer that initializes a 22k-array to add only slightly more
> than 22k to the class file! What's going on?
>
I had the same problem. It seems, that the compiler stores each element
with some type-information.
Write a example with some string-pattern in the byte-array and look
in the class-file.
> If I could solve these to problems, I would be a happy camper once
> again; but I was also thinking of a different approach: I could put
> the data into a separate file, and read that to initialize the array;
> I wouldn't even worry about compressing that file, because everything
> will eventually be put into a jar file, and that will take care of
> that. But that leads to the next problem: how do I read a file from
> the jar containing my package, if possible in such a way that the same
> code will work for an application, *and* if this jar is loaded as an
> applet? If someone could share some working code to do that, or point
> me to an example, I would be very grateful!
You can read such files from the resources (All that can be found in
Classpath,
even jar-files; even as applet) with some code like this:
public byte[] readFromResource( String name )
throws IOException
{
InputStream is =
getClass().getClassLoader().getSystemResourceAsStream( name );
// or InputStream is =
getClass().getClassLoader().getResourceAsStream( name );
if (is == null)
return null;
ByteArrayOutputStream os = new ByteArrayOutputStream( );
byte buffer[] = new byte[10240];
int len;
while ( (len = is.read( buffer, 0, buffer.length )) >= 0)
os.write( buffer, 0, len);
return os.toByteArray();
}
(sorry not tested, just try it).
If you want to read from zip-files, use ZipInputStream. Very fast and
easy to use.
Regards,
Bernd Wengenroth
--
--------------------------------------------------------
Bernd Wengenroth
IoS Gesellschaft für innovative Softwareentwicklung mbH
Donatusstraße 127-129 WWW: http://www.IoS-online.de
50259 Pulheim email: [EMAIL PROTECTED]
Tel: 02234 / 986434 Fax: 02234 / 986433