Как получить тот же массив байтов после того, как сохранил его как String? - PullRequest
1 голос
/ 26 июня 2019

Я использовал код Java для сжатия строки в байтовый массив, а затем сохраняю этот байтовый массив как строку в базе данных Cloud. Для расшифрованного сообщения требуется тот же байтовый массив, который был возвращен методом сжатия. Итак, как получить тот же байтовый массив из сохраненной строки.

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));
    }
}
...