Last active
August 22, 2016 09:16
-
-
Save vandershraaf/4e1fc8f3a05069de4b9c8c766afdd4d8 to your computer and use it in GitHub Desktop.
Storing binary file into Redis in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This example stores a binary file image ("Koala.jpg") into a local Redis server, and then | |
* retrieves it back which the finally written back to another file ("copyKoala.jpg") | |
* | |
* Dependencies: (Jedis and Commons IO) | |
* | |
* <dependency> | |
<groupId>redis.clients</groupId> | |
<artifactId>jedis</artifactId> | |
<version>2.8.1</version> | |
<type>jar</type> | |
<scope>compile</scope> | |
</dependency> | |
<dependency> | |
<groupId>commons-io</groupId> | |
<artifactId>commons-io</artifactId> | |
<version>2.5</version> | |
</dependency> | |
* @author Ashraf | |
* | |
*/ | |
package com.ashrafishak.jedistesting; | |
import java.io.FileInputStream; | |
import java.io.FileNotFoundException; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import org.apache.commons.io.IOUtils; | |
import redis.clients.jedis.BinaryJedis; | |
public class RedisBinaryStore { | |
public static void main(String[] args) { | |
// Connect to local Redis server | |
BinaryJedis binJedis = new BinaryJedis("localhost"); | |
try { | |
// Read the image file and turns it into array of bytes | |
// Then, store the bytes into Redis with the key | |
binJedis.set("/koala/my_first_face".getBytes(),IOUtils.toByteArray(new FileInputStream("Koala.jpg"))); | |
// Retrieves the image bytes using the key | |
byte[] value = binJedis.get("/koala/my_first_face".getBytes()); | |
OutputStream out = new FileOutputStream("copyKoala.jpg"); | |
// Writes the bytes to the output file | |
IOUtils.write(value, out); | |
out.close(); | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment