12

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.

Community
  • 1
  • 1
markdsievers
  • 7,151
  • 11
  • 51
  • 83

3 Answers3

13

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;
}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • That constructor doesn't exist. – BalusC Nov 30 '11 at 03:35
  • Thanks, I did checkout [StringReader](http://docs.oracle.com/javase/6/docs/api/java/io/StringReader.html), but I saw no such constructor. – markdsievers Nov 30 '11 at 03:36
  • Cheers Matt, just tried this solution successfully. Didn't use StringReader initially cause I had my blinders on looking for control over the encoding. Thanks very much for your assistance. Upvote + accept for you my friend. – markdsievers Nov 30 '11 at 03:45
  • You're quite welcome. Apologies for initially pointing you toward a nonexistent constructor. – Matt Ball Nov 30 '11 at 03:47
3
   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"))
grep
  • 5,465
  • 12
  • 60
  • 112
1

Try this:

ByteArrayInputStream bais = new ByteArrayInputStream(propertiesString.getBytes("UTF-8"));
properties.load(bais);
Óscar López
  • 232,561
  • 37
  • 312
  • 386