Drowning in IO Streams
Ive use GZIP and Byte output stream a million times with no
problem but the following code isnt working. And seeing how
the problem is in 5 lines of code I must be making a REALLY
stupid mistake, lol.
This is just a small test class to turn a String into a byte[] array
and then return a compressed byte[].
The problem is in the compress() method.
I always get the same values regardless of the text:
Buffer: [31, -117, 8, 0, 0, 0, 0, 0, 0, 0]
Compressed Byte[] Length: 10
Id appreciate a fresh pair of eyes on this.
Thanks!
import java.io.*;
import java.util.Arrays;
import java.util.zip.*;
import java.lang.reflect.*;
publicclass StringCompressor{
publicstaticvoid main(String[] args){
new StringCompressor();
}
public StringCompressor(){
try{
// output
baos =new ByteArrayOutputStream(512);
gos =new GZIPOutputStream(baos, 512);
// input
baisBuffer =newbyte[512];
bais =new ByteArrayInputStream(baisBuffer);
//gis = new GZIPInputStream(bais, 512);
// testing
test("1234567890");
test("this is some text");
test("this is a whole entire sentence full of english text");
test("Call me Ishmael. Some years ago - never mind how long precisely - " +
"having little or no money in my purse, and nothing particular to " +
"interest me on shore, I thought I would sail about a little and see "+
"the watery part of the world.");
}catch(Exception e){
e.printStackTrace();
}
}
publicvoid test(String s)throws Exception{
output(s);
byte[] storage = compress(s);
decompress(storage);
}
publicbyte[] compress(String s)throws Exception{
byte[] bytes = s.getBytes();
System.out.println("Byte[]: " + Arrays.toString(bytes));
System.out.println("Byte[] Length: " + bytes.length);
gos.write(bytes, 0, bytes.length);
gos.flush();// ?
baos.flush();// ?
byte[] output = baos.toByteArray();
System.out.println("Buffer: " + Arrays.toString(output));
System.out.println("Compressed Byte[] Length: " + output.length);
return output;
}
publicvoid decompress(byte[] storage)throws Exception{
}
publicint getCharLength(String string){
try{
Field field = (String.class).getDeclaredField("value");
field.setAccessible(true);
char[] value = (char[])field.get(string);
return value.length;
}catch(Exception e){
e.printStackTrace();
}
return -1;
}
publicvoid output(String s){
System.out.println("\nText: " + s);
System.out.println("String Length: " + s.length());
System.out.println("Char[] Length: " + getCharLength(s));
}
ByteArrayOutputStream baos;
GZIPOutputStream gos;
byte[] baisBuffer;
ByteArrayInputStream bais;
GZIPInputStream gis;
}

