0

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.

2 Answers 2

1

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

The above code will print "# #Sat Oct 27 13:59:23 IST 2018" before the list of properties. We just need only properties. This is an old post, I will find how I did this and update this later.
Have you found a solution to remove timestamp?
I think I found some alternative way of doing it. I will check and update the post.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.