Mallu Golageri
Mallu Golageri

Reputation: 59

Convert Properties object to byte array in java

I want to convert Properties object to byte[], however i can do with the following piece of code but

private byte[] getBytes(Properties properties){
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter=new PrintWriter(stringWriter);
    properties.list(printWriter);
    String fileContent = stringWriter.getBuffer().toString();
    byte[] bytes = fileContent.getBytes();
    try{
        stringWriter.close();
        printWriter.close();
    }catch (IOException e){
        log.error("unable to close resource stringWriter" + e.getStackTrace());
    }

    return bytes;
}

but properties.list(printWriter), will print the string "--listing properties--" string to the console. Need help in finding the best way to do it.

Upvotes: 0

Views: 3709

Answers (2)

Rubén Aguado
Rubén Aguado

Reputation: 366

Properties file contains plain text, so to store a byte array you need to encode bytes to plain text. The best way is to use Base64 encodec.

String Base64.econdeToString(byte[])

And to retrieve bytes:

byte[] Base64.decode(String)

Upvotes: 0

Winterwheat
Winterwheat

Reputation: 56

I used a ByteArrayOutputStream to convert a Properties object. Your function could be modified to be the following -

private byte[] getBytes(Properties properties){
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {
        props.store(byteArrayOutputStream, "");
    } catch (IOException e) {
        log.error("An error occurred while storing properties to a byte array: " + e.getStackTrace());
    }

    return byteArrayOutputStream.toByteArray();
}

Upvotes: 1

Related Questions