一、读取properties文件:
public class Properties{
public static void main(String[] args){
Properties pt = new Properties();//创建一个Properties对象
try {
String url = pt.getProperties();//调用Properties对象的getProperties()方法,接收方法返回的配置文件路径
} catch (Exception e) {
e.printStackTrace();
}
}
private String getProperties() throws IOException,
ParserConfigurationException, SAXException {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("mpxj.properties"); //将配置文件读取到输入流中
Properties properties = new Properties();
try{
properties.load(inputStream); //加载配置文件
}catch (IOException ioE){
ioE.printStackTrace();
}finally{
inputStream.close();
}
return properties.getProperty("name"); //根据配置文件properties的name获取value
}
}
配置文件如下:
name value
name e:\test.mpp
二、读取xml文件:
public class Properties{
public static void main(String[] args){
Properties pt = new Properties();//创建一个Properties对象
try {
String url = pt.getProperties();//调用Properties对象的getProperties()方法,接收方法返回的配置文件路径
} catch (Exception e) {
e.printStackTrace();
}
}
private String getProperties() throws IOException,
ParserConfigurationException, SAXException {
String value = null;//用于返回xml文件的路径
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//创建DocumentBuilder工厂
try {
DocumentBuilder db = dbf.newDocumentBuilder();//创建Document对象
Document doc = db
.parse("D:/test.xml");//获取xml配置
NodeList jarList = doc.getElementsByTagName("jar");//由于xml文件的数据结构是树的结构,所以可将其放入结
for (int i = 0; i < jarList.getLength(); i++) {
Node jar = jarList.item(i);//返回集合中的第i项
Element elem = (Element) jar;
for (Node node = jar.getFirstChild(); node != null; node = node
.getNextSibling()) {
value = node.getNodeValue();//获取标签内容
}
}
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
}
配置文件如下:
<jar id="tt" >e:\Dcits\2018.1.11—研发计划\SmartTeller10研发计划_V0.1.mpp</jar>
注:使用properties配置文件时,使用文本编辑器打开服务器上的配置文件时,中文字符等会乱码,所以最好使用xml配置文件