MatBanik
MatBanik

Reputation: 26870

More effective way to convert file to byte array to string and back

I have following way of converting file to byte array and than to string and back.

        InputStream is = new FileInputStream(new File("c:/original.png"));
        String temp = Hex.encodeHexString(IOUtils.toByteArray(is));
        System.out.println(temp);
        byte[] b = Hex.decodeHex(temp .toCharArray());
        OutputStream out = new FileOutputStream(new File("c:/copy.png"));
        IOUtils.write(b, out);

It works OK. The problem is the size of temp string. If the c:/original.png file is 1523KB than the temp size is 3046KB. Is there more effective way of converting the file to the string that would not double the size of the file? (BTW I understand why it is about twice the size)

Alternatively, how would I go about compressing the temp string?

As far as the reason for the string. It is being stored in cache that will take only strings. The file is actually upload to the web server. Once the upload is about to be downloaded it will be pulled from cache rather than the database. And the cache is there to improve search performance via predictions that I don't want calling the database each time someone searches.

Upvotes: 1

Views: 2434

Answers (1)

Daniel Earwicker
Daniel Earwicker

Reputation: 116714

A more efficient encoding than Hex is Base64, the overhead tending toward a minimum of about 37% for large files. Unfortunately there's no standard library for it, but Apache Commons contains a class to do this.

        String temp = Base64.encodeBase64String(IOUtils.toByteArray(is));            
        byte[] b = Base64.decodeBase64(s);

Upvotes: 3

Related Questions