Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTF-8 encoded Java String into Properties

I have a single UTF-8 encoded String that is a chain of key + value pairs that is required to be loaded into a Properties object. I noticed I was getting garbled characters with my intial implementation and after a bit of googling I found this Question which indicated what my problem was - basically that Properties is by default using ISO-8859-1. This implementation looked like

public Properties load(String propertiesString) {
        Properties properties = new Properties();
        try {
            properties.load(new ByteArrayInputStream(propertiesString.getBytes()));
        } catch (IOException e) {
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return properties;
    }

No encoding specified, hence my problem. To my question, I can't figure out how to chain / create a Reader / InputStream combination to pass to Properties.load() that uses the provided propertiesString and specifies the encoding. I think this is mostly due to my inexperience in I/O streams and the seemingly vast library of IO utilities in the java.io package.

Any advice appreciated.

like image 553
markdsievers Avatar asked Nov 30 '11 03:11

markdsievers


1 Answers

Use a Reader when working with strings. InputStreams are really meant for binary data.

public Properties load(String propertiesString) {
    Properties properties = new Properties();
    properties.load(new StringReader(propertiesString));
    return properties;
}
like image 139
Matt Ball Avatar answered Oct 05 '22 03:10

Matt Ball