Reputation: 41
What would be the best way to store the following Business Rules in a File so that they can be applied on the input values which would be keys?
Key-INDIA; Value-Delhi.
Key-Australia; Value-Canberra.
Key-Germany, Value-Berlin.
One Solution :- Xml
<Countries>
<India>Delhi</India>
<Australia>Canberra</Australia>
<Germany>Berlin</Germany>
</Countries>
As the number of rules are going to be > 1000; implementing it using Map is not possible.
Regards, Shreyas.
Upvotes: 0
Views: 226
Reputation: 272307
Have you looked at Spring configuration ? That way you can/create a map in config and store object definitions per key. e.g.
<map>
<entry key="India" value="Delhi">
</map>
You're talking about business rules but at the moment you're simply storing a key/value pair. If those rules become more complex then a simple key/value pair won't suffice. So perhaps you need something like:
Map<String, Country>
in your code, and Country is an object with (for now) a capital city, but in the future it would contain (say) locations, or an international phone number prefix, or a tax rule etc. In Spring it would resemble:
<map>
<entry key="India" ref="india"/>
</map>
<!-- create a subclass of Country -->
<bean id="india" class="com.example.India">
I realise this is considerably more complex than the other suggestions here. However since you're talking about rules, I suspect you'll be looking to configure/define some sort of behaviour. You can do this using properties (or similar) but likely you'll end up with different properties sets for the different behavioural aspects of your rules. That rapidly becomes a real maintenance nightmare.
Upvotes: 0
Reputation: 9476
Use .properties
file and store them in a key value pair.
India=Delhi.
Australia=Canberra.
Germany=Berlin.
And use java.util.Properties
to read that file as told by hmjd.
For Example :
Properties prop = new Properties();
try {
//load a properties file
prop.load(new FileInputStream("countries.properties"));
//get the property value and print it out
System.out.println(prop.getProperty("India"));
System.out.println(prop.getProperty("Australia"));
System.out.println(prop.getProperty("Germany"));
} catch (IOException ex) {
ex.printStackTrace();
}
Upvotes: 3
Reputation: 121971
Use java.util.Properties
to write, and read, from file:
Properties p = new Properties();
p.setProperty("Australia", "Canberra");
p.setProperty("Germany", "Berlin");
File f = new File("my.properties");
FileOutputStream fos = new FileOutputStream(f);
p.store(fos, "my properties");
Use p.load()
to read them back from file and p.getProperty()
to query them once loaded.
Upvotes: 2
Reputation: 17940
Create a properties file (like file.properties):
INDIA=Delhi.
Australia=Canberra.
Germany=Berlin.
Then in the code:
public static void main(String[] args) {
Properties prop = new Properties();
try {
prop.load(new FileInputStream("file.properties"));
String value= prop.getProperty("INDIA");
...
} catch (Exception e) {
}
}
Upvotes: 0