Redis/java - writing and reading binary data

8.8k views Asked by At

I'm trying to write and read a gzip to/from Redis. The problem is that I tried saving the read bytes to a file and opening it with gzip - it's invalid. The strings are also different when looking at them in the Eclipse console.

Here's my code:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import redis.clients.jedis.Jedis;

public class TestRedis
{

  public static void main(String[] args) throws IOException
  {
    String fileName = "D:/temp/test_write.gz";

    String jsonKey = fileName;

    Jedis jedis = new Jedis("127.0.0.1");

    byte[] jsonContent = ReadFile(new File(fileName).getPath());

    // test-write data we're storing in redis
    FileOutputStream fostream = new FileOutputStream("D:/temp/test_write_before_redis.gz"); // looks ok
    fostream.write(jsonContent);
    fostream.close();

    jedis.set(jsonKey.getBytes(), jsonContent);

    System.out.println("writing, key: " + jsonKey + ",\nvalue: " + new String(jsonContent)); // looks ok

    byte[] readJsonContent = jedis.get(jsonKey).getBytes();
    String readJsonContentString = new String(readJsonContent);
    FileOutputStream fos = new FileOutputStream("D:/temp/test_read.gz"); // invalid gz file :( 
    fos.write(readJsonContent);
    fos.close();

    System.out.println("n\nread json content from redis: " + readJsonContentString);

  }

  private static byte[] ReadFile(String aFilePath) throws IOException
  {
    Path path = Paths.get(aFilePath);
    return Files.readAllBytes(path);
  }

}
1

There are 1 answers

1
sazzad On BEST ANSWER

You are using Jedis.get(String) to read which includes an inner UTF-8 conversion. But using Jedis.set(byte[], byte[]) to write does not include such conversion. The mismatch could be because of this reason. If so, you can try Jedis.get(byte[]) to read from redis to skip UTF-8 conversion. E.g.

byte[] readJsonContent = jedis.get(jsonKey.getBytes());