Search code examples
javaarrayslzw

Copy String contents to a byte array (LZW encoding technique)


I am trying to implement LZW compression and decompression technique. My program takes any file as an InputStream and reads it into a byte array. It then applies the compression algorithm to it and the encoded bytes are returned in a string variable.

I then apply the decompression algorithm which returns back the original numbers.

Now in order to retrieve the original file I have to transfer the contents of this string into a byte array and then write this array into an outputstream.

Copying the contents of the decompressed string to a byte array is where my problem lies.

File file = new File("aaaa.png");
byte[] data = new byte[(int) file.length()];
try{
    FileInputStream in = new FileInputStream(file);
    in.read(data);
    in.close();
for(int i= 0; i< data.length;i++){
        System.out.print("original = " + data[i]);
    }
String ax = Arrays.toString(data);
List<Integer> compressed = compress(ax);
System.out.println("compressed = " + compressed);
String decompressed= new String(decompress(compressed));
System.out.println("decompressed = " + decompressed);



// Copy string contents into byte array arr[]



File file2 = new file("aaaa.png");
FileOutputStream out = new FileOutputStream(file2);
out.write(arr);
out.close();
}
catch(Exception e){
    System.out.println("Error!");
    e.printStackTrace();
}

The output for my code so far looks something link this -

orignal = -119807871131026100001373726882000170001686000.....

compressed = [91, 45, 49, 49, 57, 44, 32, 56, 48, 261, 55, 56, 265, 49, 261, 49, 51, 270, 264, 32, 50, 54, 273, 261, 274, 280, 270, 272, 32, 55, 283, 55, 50, 261, 54, 267, 262, .....]

decompressed = [-119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 17, 0, 0, 0, 16, 8, 6, 0, 0, 0, -16, 49, -108, 95, 0, 0, 0, 1, 115, 82, 71, 66, 0, -82, -50, 28, -23, 0, 0, 0, 4, 103, 65, 77, 65, 0, 0, -79, -113, 11, -4, 97, 5, 0, 0, 0, 32, 99, 72, ,......]

Please help me figure out how do I copy the contents of a string into a byte array. Thank you!


Solution

    1. String to byte[] and vice versa can be transformed like so:

      String string = "Hello!";
      byte[] array;
      //String to byte[]
      array = string.getBytes();
      //byte[] to String
      string = new String(array);
      
    2. If I understood you right you are going to parse string with byte numerical values.

      String decompressed = "[-119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72]";
      String[] input = decompressed.replaceAll("[\\[\\]]", "").split(", ");
      byte[] output = new byte[input.length];
      for (int i = 0; i < input.length; i++) {
          output[i] = Byte.parseByte(input[i]);
      }
      System.out.println(new String(output));
      

      Output is PNG and some nonprinting characters.