Sunday, August 21, 2016

Convert List String to bytes and bytes to List String

    /**
     * Convert list string to bytes array.
     *
     * @param listString
     *            the list string
     * @return the byte[]
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public static byte[] convertListStringToBytesArray(List<String> listString)
            throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DeflaterOutputStream out = new DeflaterOutputStream(baos);
        DataOutputStream dos = new DataOutputStream(out);
        for (String i : listString) {
            dos.writeUTF(i);
            ;
        }
        dos.close();
        out.close();
        baos.close();
        return baos.toByteArray();
    }

    /**
     * Convert bytes array to list string.
     *
     * @param byteArrays
     *            the byte arrays
     * @return the list
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public static List<String> convertBytesArrayToListString(byte[] byteArrays)
            throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(byteArrays);
        InflaterInputStream iis = new InflaterInputStream(bais);
        DataInputStream dins = new DataInputStream(iis);
        List<String> listRs = new ArrayList<String>();
        while (true) {
            try {
                String value = dins.readUTF();
                listRs.add(value);
            } catch (EOFException e) {
                break;
            }
        }
        dins.close();
        iis.close();
        bais.close();
        return listRs;
    }

No comments:

Post a Comment