如何读取properties文件内容 - IDC资讯网_站长学院 - Java PHP Flex Python Ajax CSS 编程 开源 学习 总结 分享

如何读取properties文件内容

[ 2008-05-29 17:49 | by 徐岳锋 ]
在java类中读取properties文件,可以这样一个类:

public class FetchHeaderImage {
  public String getImage(String providerName){
    String imageName = "ed_header_top_logos.jpg";
    try{  
        InputStream in = getClass().getResourceAsStream("headerImage.properties");
        Properties p = new Properties();
        p.load(in);
        imageName = p.get(providerName).toString();
    }catch(Exception e){      
      System.out.println("There is a exception");
      e.printStackTrace();
    }
    return imageName;
  }
  public static void main(String[] args){
    FetchHeaderImage hi = new FetchHeaderImage();
    String imageName = hi.getImage("dddd");
    System.out.println("imageName=" + imageName);
  }
}


在这里,headerImage.properties与此FetchHeaderImage 类在同一文件下,当headerImage里有dddd=b.jpg时,运行此类就会显示
imageName=b.jpg


下面的方法是知道的headerImage.properties文件的全路径,运行结果与上面一样

public class FetchHeaderImage {
  public String getImage(String providerName){
    String imageName = "ed_header_top_logos.jpg";
    try{
       String path = "C:\\\\\\\\\\……………\\";
       String fileName = "headerImage.properties";
       InputStream in = new FileInputStream(path + fileName);
       ResourceBundle rb = new PropertyResourceBundle(in);
       imageName = rb.getString(providerName);
    }catch(Exception e){      
      System.out.println("There is a exception");
      e.printStackTrace();
    }
    return imageName;
  }
  public static void main(String[] args){
    FetchHeaderImage hi = new FetchHeaderImage();
    String imageName = hi.getImage("dddd");
    System.out.println("imageName=" + imageName);
  }
}

参考资料:
http://tech.163.com/06/0407/09/2E3J5B150009159T.html
http://topic.csdn.net/t/20020704/09/848764.html
http://hi.baidu.com/alizv/blog/item/d8cb2af4094662dbf3d38539.html
编程语言 | 评论(0) | 引用(0) | 阅读(6659)