简体   繁体   中英

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.

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

public Properties load(String propertiesString) {
    Properties properties = new Properties();
    properties.load(new StringReader(propertiesString));
    return properties;
}
   private Properties getProperties() throws IOException {
        ClassLoader classLoader = getClass().getClassLoader();
        InputStream input = classLoader.getResourceAsStream("your file");
        InputStreamReader inputStreamReader = new InputStreamReader(input, "UTF-8");
        Properties properties = new Properties();
        properties.load(inputStreamReader);
        return properties;
    }

then usage

System.out.println(getProperties().getProperty("key"))

Try this:

ByteArrayInputStream bais = new ByteArrayInputStream(propertiesString.getBytes("UTF-8"));
properties.load(bais);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM