java 获取配置文件里的文件,常用的方法

第一种方法是读取.xml 方法


1.实体Setting.java


public class Setting {


/**前台结果返回地址 */
private String frontUrl;

/**后台结果返回地址 */
private String backUrl;


public String getFrontUrl() {
return frontUrl;
}


public void setFrontUrl(String frontUrl) {
this.frontUrl = frontUrl;
}


public String getBackUrl() {
return backUrl;
}


public void setBackUrl(String backUrl) {
this.backUrl = backUrl;
}

}

2.pft.xml 

<?xml version="1.0" encoding="UTF-8"?>
<a>

       <setting name="frontUrl" value="http://localhost:8080/test/pay/t1.jhtml" />
<setting name="backUrl" value="http://localhost:8080/test/pay/t2.jhtm" />

</a>

 3.     

import java.io.File;
import java.io.IOException;
import java.util.List;


import org.apache.commons.beanutils.BeanUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ClassPathResource;




public class test {

public static void main(String[] args) throws IOException, DocumentException {

 

                      Setting setting = new Setting();//实体,主要是针对配置文件里的xml的字段。
File file= new ClassPathResource("pft..xml").getFile();
Document document = new SAXReader().read(file);
List<Element> elements = document.selectNodes("/aa/setting");
for (Element element : elements) {
String name = element.attributeValue("name");
String value = element.attributeValue("value");
try {
BeanUtils.setProperty(setting, name, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

System.out.println(setting.getBackUrl());
}
}

第二种读取的是.property方法



import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class test {
public static void main(String[] args) throws IOException  {
InputStream inputStream;      
ClassLoader cl = test. class .getClassLoader();      
if  (cl !=  null ) {      
        inputStream = cl.getResourceAsStream( "log4j.properties" );      
}  else {      
        inputStream = ClassLoader.getSystemResourceAsStream( "log4j.properties" );      
}      
Properties dbProps =  new  Properties();   
System.out.println(inputStream+"--------------");
dbProps.load(inputStream);      
inputStream.close(); 
System.out.println(dbProps.getProperty("log4j.log"));
}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值