Java: gzip di un array di byte in un altro array di byte (senza scritture su disco)

Ecco la funzione che utilizza un ByteArrayOutputStream:

 
	public static byte[] gzip(byte[] data) throws IOException {
 
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
 
		GZIPOutputStream zos = new GZIPOutputStream(bos);
		zos.write(data);
 
		zos.close();
		bos.close();
 
		return bos.toByteArray();
	}

Per esempio, per applicarlo ad una stringa:

 
String s = "Nel mezzo del cammin di nostra vita";
 
byte[] b = s.getBytes();
byte[] c = Strings.gzip(b);
 
System.out.println(new String(c));

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>