Reputation: 18171
I reed properties file:
InputStream input = new FileInputStream("data.ini");
Reader reader = new InputStreamReader(input, Charset.forName("UTF-8"));
Properties prop = new Properties();
prop.load(reader);
My properties file Key
contains space and I need to put \
character to read it correctly. Is it possible somehow not place \
character in properties file and read it in correct way?
Properties file content:
aaa\ bbb=0
Upvotes: 2
Views: 2583
Reputation: 2520
It is not as clean as using the built in reader, but it is possible with the following code.
public static Properties load(File file) throws IOException {
InputStream input = new FileInputStream(file);
Reader reader = new InputStreamReader(input, StandardCharsets.UTF_8);
Properties p;
try (BufferedReader br = new BufferedReader(reader)) {
p = new Properties();
String line;
while ((line = br.readLine()) != null) {
int index = line.indexOf('=');
if (index > 0) {
String key = line.substring(0, index).trim();
String value = line.substring(index + 1).trim();
p.put(key, value);
}
}
}
return p;
}
Upvotes: 1
Reputation: 1025
It is possible to load properties from an XML file also... makes for neater code.
properties.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Sample Properties file in XML</comment>
<entry key="PropertyWithoutSpaces">Property value</entry>
<entry key="Property With Spaces">Property value</entry>
</properties>
PropertyTest.java:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertyTest {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.loadFromXML( new FileInputStream("properties.xml") );
System.out.println( properties.getProperty("Property With Spaces") );
System.out.println( properties.getProperty("PropertyWithoutSpaces") );
}
}
Upvotes: 0
Reputation: 1011
you can escape every thing in properties file with Java Unicode, \u0020 for whitespace,use it your problem will get solve.
Upvotes: 1
Reputation: 10549
As described in load JavaDoc:
The key contains all of the characters in the line starting with the first non-white space character and up to, but not including, the first unescaped '=', ':', or white space character other than a line terminator.
So the answer is no.
Typically keys contain other separator, my experience is that '.'
is used.
aaa.bbb=0
Upvotes: 2