String 在java中将属性对象转换为字节数组

String 在java中将属性对象转换为字节数组,string,properties,byte,String,Properties,Byte,我想将Properties对象转换为byte[],但是我可以使用下面的代码,但是 private byte[] getBytes(Properties properties){ StringWriter stringWriter = new StringWriter(); PrintWriter printWriter=new PrintWriter(stringWriter); properties.list(printWriter); String fileC

我想将Properties对象转换为byte[],但是我可以使用下面的代码,但是

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

但是properties.list(printWriter)将把字符串--listing properties--“打印到控制台。需要帮助找到最佳方法。

我使用ByteArrayOutputStream转换属性对象。您的功能可以修改为以下内容-

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

属性文件包含纯文本,所以要存储字节数组,需要将字节编码为纯文本。最好的方法是使用Base64 encodec

String Base64.econdeToString(byte[])
和检索字节:

byte[] Base64.decode(String)

上述代码将在物业列表前打印“##Sat Oct 27 13:59:23 IST 2018”。我们只需要财产。这是一篇老文章,我会找到我是如何做到这一点的,稍后会更新。你找到了一个解决方案来删除时间戳吗?我想我找到了一些替代方法。我会检查并更新帖子。