将相同的字节数组存储为字符串后,如何获得相同的字节数组?

时间:2019-06-26 08:59:48

标签: java encoding character-encoding text-compression

我已经使用Java代码将字符串压缩为字节数组,然后将该字节数组作为字符串存储在Cloud数据库中。解密后的消息需要使用compress方法返回的相同字节数组。那么如何从存储的字符串中获取相同的字节数组。

public class Gzip {

    public static byte[] compress(String data) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
        GZIPOutputStream gzip = new GZIPOutputStream(bos);
        gzip.write(data.getBytes());
        gzip.close();
        byte[] compressed = bos.toByteArray();
        bos.close();
        return compressed;
    }

    public static String decompress(String temp) throws IOException {
        String decodeData =  new String(Base64.getDecoder().decode(temp));

        byte[] compressed = decodeData.getBytes();
        ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
        GZIPInputStream gis = new GZIPInputStream(bis);
        BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        gis.close();
        bis.close();
        return sb.toString();
    }
    public static void main(String args[]) throws IOException{
        Gzip gzip = new Gzip();
        String plaintext = "Although there are many short stories. ";
        byte[] enbyte = gzip.compress(l);
        String enStr = String.valueOf(enbyte);
        // then stored enStr in cloud database
        //how to get same byte array as 'enbyte' from the 'enStr'
        //if you could modify the methods to return and get string this will             //also be helpfull 
         byte[] newbyte = ???? // 
        System.out.println(gzip.decompress(newbyte));
    }
}

0 个答案:

没有答案