PDA

View Full Version : [java] problemi con java.util.zip


ceres80
17-05-2006, 11:47
Salve,
Ho un problema con java.util.zip:
ho una stringa la voglio comprimere e memorizzare la stringa compressa in un altra stringa o array di byte e non in un file. Mi servirebbe anche poter decomprimere la stringa compressa e rimemorizzarla in una stringa decompressa. Su internet ho trovato solo tutorial su come usare java.util.zip, perņ memorizzando su file .zip e leggendo da file .zip.
Grazie

andbin
17-05-2006, 12:41
ho una stringa la voglio comprimere e memorizzare la stringa compressa in un altra stringa o array di byte e non in un file. Mi servirebbe anche poter decomprimere la stringa compressa e rimemorizzarla in una stringa decompressa. Su internet ho trovato solo tutorial su come usare java.util.zip, perņ memorizzando su file .zip e leggendo da file .zip.Ecco un esempio di compressione/decompressione di una stringa:
String str = "Ciao da Andrea";

try
{
/*---- Compressione ----*/
byte[] buff = str.getBytes ("UTF-8");

Deflater defl = new Deflater ();

defl.setLevel (Deflater.BEST_COMPRESSION);
defl.setInput (buff);
defl.finish ();

ByteArrayOutputStream bosDefl = new ByteArrayOutputStream (buff.length);

byte[] tmpDefl = new byte[256];

while (!defl.finished ())
{
int count = defl.deflate (tmpDefl);
bosDefl.write (tmpDefl, 0, count);
}

byte[] compressed = bosDefl.toByteArray ();


/*---- Decompressione ----*/
Inflater infl = new Inflater ();
infl.setInput (compressed);

ByteArrayOutputStream bosInfl = new ByteArrayOutputStream (compressed.length);

byte[] tmpInfl = new byte[256];

while (!infl.finished ())
{
int count = infl.inflate (tmpInfl);
bosInfl.write (tmpInfl, 0, count);
}

byte[] decompressed = bosInfl.toByteArray ();


String output = new String (decompressed, "UTF-8");
System.out.println (output);
}
catch (UnsupportedEncodingException uee)
{
uee.printStackTrace ();
}
catch (DataFormatException dfe)
{
dfe.printStackTrace ();
}

ceres80
17-05-2006, 13:11
Grazie