JAVA零配置读取配置文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA零配置读取配置文件相关的知识,希望对你有一定的参考价值。
怎么读取配置文件到java中,就是不要配置文件或者写一个数据库连接配置properties,读进来,现在实现了其他的,就是读取不了配置文件,老是报错
package resources;import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;
public class DbUtil
public static Connection getConnection()
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
//读取类路径下的 jdbc.properties 文件,我的配置文件放在src包下
InputStream in = DbUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
try
properties.load(in);
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("username");
password = properties.getProperty("password");
Driver driver = null;
try
driver = (Driver) Class.forName(driverClass).newInstance();
catch (InstantiationException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IllegalAccessException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (ClassNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
Properties info = new Properties();
info.put("user", user);
info.put("password", password);
//通过 Driver 的 connect 方法获取数据库连接.
Connection connection = null;
try
connection = driver.connect(jdbcUrl, info);
catch (SQLException e)
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("----The database is connected----");
return connection;
jdbc.properties内容如下:
driver=oracle.jdbc.driver.OracleDriver#jdbcUrl=jdbc\\:oracle\\:thin\\:@10.91.4.102\\:1521\\:orcljdbcUrl=jdbc\\:oracle\\:thin\\:@127.0.0.1\\:1521\\:orcl
username=cp2
password=cp2test
//调用方法
public static void main(String[] args)
String id = "111111";
String gread = "3";
List<Student> sList = new ArrayList<Student>();
Connection con = DbUtilCR.getConnection();
PreparedStatement pre = null;
ResultSet result = null;
String sql = "select s.name,s.age from student s where s.id=? and s.gread=?";
try
pre = con.prepareStatement(sql);
pre.setString(1, id);//传参数学号
pre.setString(2, gread);//传参数年级
result = pre.executeQuery();
System.out.println("执行SQL为:["+sql+"]");
System.out.println("参数为:["+id+","+gread+"]");
while (result.next())
Student st = new Student();
st.setName(result.getString("name"));//与查询出的字段或者别名保持一致
st.setAge(result.getString("age"));
sList.add(st);
catch (SQLException e)
// TODO Auto-generated catch block
e.printStackTrace();
for (int i = 0;i<sList.size();i++)
System.out.println("姓名:"+sList.get(i).getName()+"\\t年龄:"+sList.get(i).getAge());
参考技术A 数据库驱动没有读到,你用配置文件读还是用代码读 贴出来看看,
java如何读取XML配置文件
<?xml version="1.0" encoding="utf-8"?>
<appset>
<bao>test</bao>
<lei>class</lei>
<bianliang>a</bianliang>
</appset>
例如这样的一个简单XML的配置文件, 我想用java读取文件里的test,class,a应该如何读取呢,求详细代码!
一、XML文件
这个示例文件包括了用来打开ORACLE数据库的各种参数
<?xml version="1.0" encoding="UTF-8"?>
<dbmsg>
<dbinfo>
<drivername>oracle.jdbc.driver.OracleDriver</drivername>
<sConnStr>jdbc:oracle:thin:@11.88.225.80:1521:VOUCHERDB</sConnStr>
<username>SYS AS SYSDBA</username>
<password>voucherdb</password>
</dbinfo>
</dbmsg>
二、编写类名为ReadXml的类,用于解析XML文件
我们要在应用程序中打开数据库,就必须完成对该文件中drivername、sConnStr、username、password的读取,通过查找有关资料,笔者编制了以下程序,用于读取文件名为filename的XML文件。
package voucher.basic;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ReadXml
private String drivername;
private String sConnStr;
private String username;
private String password;
public String getDrivername()
return drivername;
public String getSConnStr()
return sConnStr;
public String getUsername()
return username;
public String getPassword()
return password;
public void setDrivername(String drivername)
this.drivername = drivername;
public void setSConnStr(String connStr)
sConnStr = connStr;
public void setUsername(String username)
this.username = username;
public void setPassword(String password)
this.password = password;
public ReadXml(String fileName)
DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
try
DocumentBuilder dombuilder=domfac.newDocumentBuilder();
InputStream is=new FileInputStream(fileName);
Document doc=dombuilder.parse(is);
Element root=doc.getDocumentElement();
NodeList dbinfo=root.getChildNodes();
if(dbinfo!=null)
for(int i=0;i<dbinfo.getLength();i++)
Node db=dbinfo.item(i);
for(Node node=db.getFirstChild();node!=null;node=node.getNextSibling())
if(node.getNodeType()==Node.ELEMENT_NODE)
if(node.getNodeName().equals("drivername"))
setDrivername(node.getFirstChild().getNodeValue());
if(node.getNodeName().equals("sConnStr"))
setSConnStr(node.getFirstChild().getNodeValue());
if(node.getNodeName().equals("username"))
setUsername(node.getFirstChild().getNodeValue());
if(node.getNodeName().equals("password"))
setPassword(node.getFirstChild().getNodeValue());
catch (ParserConfigurationException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (FileNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (SAXException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
这个以ReadXml命名的类,使用了参数为文件名的构造方法,用户只要将配置文件我名称传递给该方法,就可以完成对XML文件的解析,进而完成对相应参数数的读取。
三、如何获取XML文件全路径并读取配置参数
获取XML文件全路径的方法有两个,一是在servlet中获取,二是在单独的JAVA类中获取。
1.在servlet中获取XML文件的全路径并读取配置参数
程序片段String dirPath = getServletContext().getRealPath( "/WEB-INF");
String fileName = dirPath + "/conn.xml";
ReadXml xm = new ReadXml(fileName);
String DriverName = xm.getDrivername();
String connStr = xm.getSConnStr();
String user = xm.getUsername();
String pas = xm.getPassword();
将这段程序添加到servlet中dopost()之后即可完成参数的读取
2.在单独的JAVA类中获取全路径并读取配置参数
程序片段
String dirpath = System.getProperty("user.dir");
String xmlFile = dirpath + "/WebRoot/WEB-INF/conn.xml";
ReadXml rdxml = new ReadXml(xmlFile);
String driverName = rdxml.getDrivername();
String sConnStr = rdxml.getSConnStr();
String userName = rdxml.getUsername();
String passWord = rdxml.getPassword();
注:配置文件conn.xml保存在webroot/WEB-INF目录中。 参考技术A java读取xml有4种方式:
1.dom
2.jdom
3.dom4j
4.sax
我给你看dom解析的代码吧
public class DOM
public static void main(String args[])
try
File f = new File("myfile.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
NodeList nl = doc.getElementsByTagName("appset");
for (int i = 0; i < nl.getLength(); i++)
System.out.println(doc.getElementsByTagName("bao").item(i).getFirstChild().getNodeValue());
System.out.println(doc.getElementsByTagName("lei").item(i).getFirstChild().getNodeValue());
System.out.println(doc.getElementsByTagName("bianliang").item(i).getFirstChild().getNodeValue());
catch (Exception e)
e.printStackTrace();
运行一下结果就出来了。本回答被提问者采纳 参考技术B /***
* 读取xml中存的字段名
*/
public static String getFiledsForXml(int index) throws Exception
DocumentBuilderFactory dbfactory;
DocumentBuilder domparser;
Document doc;
Element root = null;
try
dbfactory = DocumentBuilderFactory.newInstance();
domparser = dbfactory.newDocumentBuilder();
doc = domparser.parse(new File("FileUpload.xml"));
root = doc.getDocumentElement();
catch (Exception e)
e.printStackTrace();
if (root != null)
return root.getElementsByTagName("sql").item(index).getAttributes()
.getNamedItem("field").getNodeValue();
else
return "";
参考技术C 学一下jdom吧,很简单的,可以很方便的提取xml的值,网上很多相关教程(推荐张龙的xml培训视频) 参考技术D 你想用哪种方式读
以上是关于JAVA零配置读取配置文件的主要内容,如果未能解决你的问题,请参考以下文章