0

将以下业务规则存储在文件中以便它们可以应用于作为键的输入值的最佳方法是什么?

Key-INDIA; Value-Delhi.
Key-Australia; Value-Canberra.
Key-Germany, Value-Berlin.

一种解决方案:- Xml

<Countries>
  <India>Delhi</India>
  <Australia>Canberra</Australia>
  <Germany>Berlin</Germany>
</Countries>

由于规则的数量将> 1000;使用 Map 实现它是不可能的。

问候,Shreyas。

4

4 回答 4

3

使用.properties文件并将它们存储在键值对中。

India=Delhi.
Australia=Canberra.
Germany=Berlin.

并用于java.util.Properties按照 hmjd 的指示读取该文件。

例如 :

       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();
        }
于 2012-07-10T11:20:35.930 回答
2

用于java.util.Properties从文件写入和读取:

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");

用于p.load()从文件中读回它们并p.getProperty()在加载后查询它们。

于 2012-07-10T11:19:40.977 回答
0

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) {
            }
    }
于 2012-07-10T11:23:29.407 回答
0

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.

于 2012-07-10T11:23:51.737 回答