Sto provando a scrivere una classe che può comprimere i dati. Il codice seguente non riesce (non viene generata alcuna eccezione, ma il file .gz di destinazione è vuoto.)
Inoltre: Non voglio generare il file .gz direttamente come è stato fatto in tutti gli esempi. Voglio solo ottenere i dati compressi , in modo che io possa ad es. crittografarlo prima di scrivere i dati su un file.Compressione GZIP su un array di byte
Se scrivo direttamente in un file tutto funziona bene:
import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;
public class Zipper
{
public static void main(String[] args)
{
byte[] dataToCompress = "This is the test data."
.getBytes(StandardCharsets.ISO_8859_1);
GZIPOutputStream zipStream = null;
FileOutputStream fileStream = null;
try
{
fileStream = new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
zipStream = new GZIPOutputStream(fileStream);
zipStream.write(dataToCompress);
fileStream.write(compressedData);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try{ zipStream.close(); }
catch(Exception e){ }
try{ fileStream.close(); }
catch(Exception e){ }
}
}
}
Ma, se voglio 'bypass' al array di byte streaming non produce un singolo byte - compressedData
è sempre vuoto.
import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;
public class Zipper
{
public static void main(String[] args)
{
byte[] dataToCompress = "This is the test data."
.getBytes(StandardCharsets.ISO_8859_1);
byte[] compressedData = null;
GZIPOutputStream zipStream = null;
ByteArrayOutputStream byteStream = null;
FileOutputStream fileStream = null;
try
{
byteStream = new ByteArrayOutputStream(dataToCompress.length);
zipStream = new GZIPOutputStream(byteStream);
zipStream.write(dataToCompress);
compressedData = byteStream.toByteArray();
fileStream = new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
fileStream.write(compressedData);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try{ zipStream.close(); }
catch(Exception e){ }
try{ byteStream.close(); }
catch(Exception e){ }
try{ fileStream.close(); }
catch(Exception e){ }
}
}
}
"* Il codice sottostante non riesce *" non è un messaggio di errore Java valido. –
Si prega di includere anche la traccia dello stack dall'errore. –
Genera semplicemente un file che non è un archivio ZIP. Non c'è nessun messaggio di errore. –