1

"RATNAGIRI GAS \u0026 POWER" is the data in properties file. When read to the application, it is getting converted to "RATNAGIRI GAS & POWER". Character type conversion is happening here. How to stop this automatic conversion?

This is how I load the properties file . Kindly share your ideas on why it is happening and how to read string as it is in properties file.

Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream(properties_name);
property.load(in);
Robin Green
  • 32,079
  • 16
  • 104
  • 187
om39a
  • 1,406
  • 4
  • 20
  • 39
  • This is how properties files work. Why do you want to read raw string? What is your use-case? – Pavel Horal Nov 08 '13 at 19:55
  • Needed for test cases. I need to compare the value form the Database which is a raw string with the ones I have in test cases. – om39a Nov 08 '13 at 20:03
  • Then don't load it as Properties, but read it as a text file. Or escape the unicode escape sequences. – Pavel Horal Nov 08 '13 at 20:17
  • How to escape unicode sequence? Is there any feature available in API or we need to manually do it? – om39a Nov 08 '13 at 22:44
  • 1
    You need to do it manually as Mena showed in his answer (use backslash to escape the initial unicode sequence backslash). Or you can read the file into string and replace backslashes with two backslashes before loading it into Properties. However I still don't quite understand the use case... you have properties file contents inside database? – Pavel Horal Nov 09 '13 at 15:28
  • Finally ended up with reading from text file. – om39a Nov 13 '13 at 16:20

1 Answers1

2

I don't think there's a clean way to do that.

What you can do is escape your unicode representations in the property files, or hack-convert the chosen character(s) back to their unicode representation.

Small example below on the first "solution". Not very proud of this answer.

Code

Properties p = new Properties();
InputStream s = Main.class.getClassLoader().getResourceAsStream("test/test.properties");
try {
    p.load(s);
    System.out.println(p.get("key"));
    System.out.println(p.get("rawKey"));
}
catch (IOException ioe) {
    ioe.printStackTrace();
}

test.properties file in test package

key=\u0026
rawKey=\\u0026

Output

&
\u0026

You might want to check this for the "converting-back-to-unicode" "solution".

Community
  • 1
  • 1
Mena
  • 47,782
  • 11
  • 87
  • 106