Java读取XML配置文件

1.定义webConfiguration.xml文件(名字随取)
在这里插入图片描述
2.定义对应配置文件实体类
import java.io.Serializable;//实现序列化接口是为方便转成文件,对应JSON
public class WebConfiguratinEntity implements Serializable{
private static final long serialVersionUID = 8355147750307144843L;
private String FolderPath;
public String getFolderPath() {
return FolderPath;
}
public void setFolderPath(String folderPath) {
FolderPath = folderPath;
}
}
3.测试类
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.AnyTypePermission;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class TestReadConfig {
//配置文件路径
private static String xmlPath=“com/config/webConfiguration.xml”;
public static void main(String args[]) throws Exception{
//TestReadConfig类与excel同级的,读到相对路径
//在resources目录创建excel目录并且随便写个文件
String path=TestReadConfig.class.getClassLoader().getResource(“excel/”).getPath();
// 从配置文件读取信息,读到xml文件FolderPath标签的值,绝对路径
private String FolderPath = TestReadConfig.readXML().getFolderPath();
}
/读取配置文件/
public static WebConfiguratinEntity readXML(String xmlPath) throws Exception{
//创建XStream对象
XStream xs=new XStream();
//创建xml文件缓冲流
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(TestReadConfig.class.getClassLoader().getResourceAsStream(xmlPath),“utf-8”));
StringBuilder sb=new StringBuilder();//创建StringBuilder对象
String temp=null;
while((temp=bufferedReader.readLine())!=null){
sb.append(temp);
}
String s=new String(sb);
XStream.setupDefaultSecurity(xs);
xs.addPermission(AnyTypePermission.ANY);
xs.alias(“config”,WebConfiguratinEntity.class);
WebConfiguratinEntity result=(WebConfiguratinEntity)xs.fromXML(s);
bufferedReader.close();
return result;
}
}

猜你喜欢

转载自blog.csdn.net/weixin_43686722/article/details/84331085