通过Properties类从文件中读取配置信息,从而可以避免大量的代码修改。
1、新建fruit.properties(文件名任意,路径在项目默认目录下),并写入内容:
1 apple=properties.Apple 2 banana=properties.Banana
2、编写Fruit接口:
1 public interface Fruit { 2 void eat(); 3 }
3、Fruit接口的实现类:
public class Banana implements Fruit{ @Override public void eat() { // TODO Auto-generated method stub System.out.println("Banana!"); } }
1 public class Apple implements Fruit{ 2 3 @Override 4 public void eat() { 5 // TODO Auto-generated method stub 6 System.out.println("Apple!"); 7 } 8 9 }
4、FruitFactory工厂:
1 public class FruitFactory { 2 public static Fruit getFruitInstance(String className) { 3 Fruit fruit = null; 4 try { 5 fruit = (Fruit) Class.forName(className).newInstance(); 6 } catch (Exception e) { 7 // TODO Auto-generated catch block 8 e.printStackTrace(); 9 } 10 return fruit; 11 } 12 }
5、主类:
public static void main(String[] args) { FruitFactory.getFruitInstance(Apple.class.getName()).eat(); Properties pro = init(); // Properties根据键值对获取信息 Fruit f = FruitFactory.getFruitInstance(pro.getProperty("banana")); f.eat(); System.out.println(pro.getProperty("iapple")); } static Properties init() { // 新建Properties对象 Properties pro = new Properties(); File file = new File("fruit.properties"); if (file.exists()) { try { pro.load(new FileInputStream(file)); pro.setProperty("iapple", "properties.iApple"); // 根据键值对将数据写入文件中 pro.store(new FileOutputStream(file), "iapple"); // pro.clear(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { pro.setProperty("apple", "properties.Apple"); // pro.loadFromXML(new FileInputStream("")); } return pro; }
运行结果:
Banana!
properties.iApple
可以用Properties#store(InputStream in,String key)将数据写入指定文件中。用Properties#clear()清除文件中所有数据。
通过Properties获取JVM配置信息:
1 Properties pro= System.getProperties(); 2 pro.list(System.out);
以键值对形式显示Properties文件中所有配置信息:
1 void showDetail() { 2 Properties pro = System.getProperties(); 3 pro.list(System.out); 4 Enumeration<?> enu = pro.propertyNames(); 5 while (enu.hasMoreElements()) { 6 String key = (String) enu.nextElement(); 7 String value = pro.getProperty(key); 8 System.out.println("key:" + key + " value:" + value); 9 } 10 }
java中Properties类的操作:http://www.cnblogs.com/bakari/p/3562244.html
java读取Properties文件的六种方法:http://blog.csdn.net/Senton/article/details/4083127