java制作工具类获取配置文件|Java读取配置文件的几种方法以及路径问题

A. java读取配置文件的几种方法以及路径问题

.类加载器读取:只能读取classes或者类路径中的任意资源,但是不适合读取特别大的资源。 ①获取类加载器 ClassLoader cl = 类名.class.getClassLoader(); ②调用类加载器对象的方法:public URL getResource(String name); 此方法查找具有给定名称的资源,资源的搜索路径是虚拟机的内置类加载器的路径。 类 URL 代表一个统一资源定位符,它是指向互联网”资源”的指针。 资源可以是简单的文件或目录,也可以是对更为复杂的对象的引用. URL对象方法:public String getPath(),获取此 URL 的路径部分。 示例代码:2.类加载器读取:只能读取classes或者类路径中的任意资源,但是不适合读取特别大的资源。 ①获取类加载器 ClassLoader cl = 类名.class.getClassLoader(); ②调用类加载器对象的方法:public InputStream getResourceAsStream(String name); 返回读取指定资源的输入流。资源的搜索路径是虚拟机的内置类加载器的路径。

B. java读取properties配置文件路径问题

可以直接通过Thread方法直接获取到项目路径下的配置文件: static { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("BankConPort.properties"); //加载线程文件成为流 Properties prop = new Properties(); try { prop.load(is);//直接转换为对象 BOB_ReqURI = prop.getProperty("BOB_ReqURI"); BOB_SignURI = prop.getProperty("BOB_SignURI"); BOBLOGINPASSword = prop.getProperty("BOBLOGINPASSWORD"); } catch (IOException ex) { java.util.logging.Logger.getLogger(BOBUtil.class.getName()).log(Level.SEVERE, null, ex); } finally { if (is != null) { try { is.close(); } catch (IOException e) { Log.info("解析信息出错", e.getMessage()); } } } }

C. java文件怎么获取项目下的配置文件

不同的配置文件 用不同的方法啊xml格式的 用dom4j对象流格式的用对象流读取,普通的文本格式,自己解析呗

D. Java 获取配置文件路径

读取配置文件 , xxx.properties放在webroot/WEB-INF/classes/目录下首先将配置文件转换成InputStream,有两种方式,原理一样,都是通过类加载器得到资源: (1)InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("xx.properties"); (2) InputStream inputStream =this.getClass() .getClassLoader().getResourceAsStream( "xx.properties" );调用对象的getClass()方法是获得对象当前的类类型,这部分数据存在方法区中,而后在类类型上调用 getClassLoader()方法是得到当前类型的类加载器,我们知道在Java中所有的类都是通过加载器加载到虚拟机中的,而且类加载器之间存在父 子关系,就是子知道父,父不知道子,这样不同的子加载的类型之间是无法访问的(虽然它们都被放在方法区中),所以在这里通过当前类的加载器来加载资源也就 是保证是和类类型同一个加载器加载的。最后调用了类加载器的getResourceAsStream()方法来加载资源。 (3) 然后加载配置文件,读取属性值 Properties prop = new Properties(); prop.load(input); String value = prop.getProperty("PropertyName"); input.close();

E. java读取配置文件的方法(xml)

用的是jdom包URL url = RederXml.class.getClassLoader().getResource(""); String path = url.toString() + "/config.xml";\\工程种xml的路径 HashMap<String, String> map = new HashMap<String, String>(); SAXBuilder sax = new SAXBuilder(); Document doc = null; try { doc = sax.build(path); } catch (JDOMException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Element root = doc.getRootElement();

F. JAVA中如何读取src下所有的properties文件

最常用读取properties文件的方法InputStream in = getClass().getResourceAsStream("资源Name");这种方式要求properties文件和当前类在同一文件夹下面。如果在不同的包中,必须使用:InputStream ins = this.getClass().getResourceAsStream("/cn/zhao/properties/testPropertiesPath2.properties");Java中获取路径方法获取路径的一个简单实现反射方式获取properties文件的三种方式1 反射方式获取properties文件最常用方法以及思考:Java读取properties文件的方法比较多,网上最多的文章是"Java读取properties文件的六种方法",但在Java应用中,最常用还是通过java.lang.Class类的getResourceAsStream(String name) 方法来实现,但众多读取properties文件的代码中,都会这么做:InputStream in = getClass().getResourceAsStream("资源Name");这里面有个问题,就是getClass()调用的时候默认省略了this,this是不能在static(静态)方法或者static块中使用的,原因是static类型的方法或者代码块是属于类本身的,不属于某个对象,而this本身就代表当前对象,而静态方法或者块调用的时候是不用初始化对象的。问题是:假如不想让某个类有对象,那么会将此类的默认构造方法设为私有,当然也不会写别的共有的构造方法。并且我这个类是工具类,都是静态的方法和变量,要在静态块或者静态方法中获取properties文件,这个方法就行不通了。其实这个类就不是这么用的,他仅仅是需要获取一个Class对象就可以了,那就容易了,取所有类的父类Object,用Object.class比用正在写类自身方便安全,下面给出一个例子,以方便交流。 import java.util.Properties; import java.io.InputStream; import java.io.IOException; /** * 读取Properties文件的例子 * File: TestProperties.java * User: leimin * Date: 2008-2-15 18:38:40 */ public final class TestProperties { private static String param1; private static String param2; static { Properties prop = new Properties(); InputStream in = Object. class .getResourceAsStream( "/test.properties" ); try { prop.load(in); param1 = prop.getProperty( "initYears1" ).trim(); param2 = prop.getProperty( "initYears2" ).trim(); } catch (IOException e) { e.printStackTrace(); } } /** * 私有构造方法,不需要创建对象 */ private TestProperties() { } public static String getParam1() { return param1; } public static String getParam2() { return param2; } public static void main(String args[]){ System.out.println(getParam1()); System.out.println(getParam2()); } } 运行结果: 151 152 当然,把Object.class换成int.class也行。另外,如果是static方法或块中读取Properties文件,还有一种最保险的方法,就是这个类的本身名字来直接获取Class对象,比如本例中可写成TestProperties.class,这样做是最保险的方法。2 获取路径的方式:File fileB = new File( this .getClass().getResource( "" ).getPath()); System. out .println( "fileB path: " + fileB); 2.2获取当前类所在的工程名:System. out .println("user.dir path: " + System. getProperty ("user.dir"))<span style="background-color: white;">3 获取路径的一个简单的Java实现</span> /** *获取项目的相对路径下文件的绝对路径 * * @param parentDir *目标文件的父目录,例如说,工程的目录下,有lib与bin和conf目录,那么程序运行于lib or * bin,那么需要的配置文件却是conf里面,则需要找到该配置文件的绝对路径 * @param fileName *文件名 * @return一个绝对路径 */ public static String getPath(String parentDir, String fileName) { String path = null; String userdir = System.getProperty("user.dir"); String userdirName = new File(userdir).getName(); if (userdirName.equalsIgnoreCase("lib") || userdirName.equalsIgnoreCase("bin")) { File newf = new File(userdir); File newp = new File(newf.getParent()); if (fileName.trim().equals("")) { path = newp.getPath() + File.separator + parentDir; } else { path = newp.getPath() + File.separator + parentDir + File.separator + fileName; } } else { if (fileName.trim().equals("")) { path = userdir + File.separator + parentDir; } else { path = userdir + File.separator + parentDir + File.separator + fileName; } } return path; } 4 利用反射的方式获取路径:InputStream ips1 = Enumeration . class .getClassLoader() .getResourceAsStream( "cn/zhao/enumStudy/testPropertiesPath1.properties" ); InputStream ips2 = Enumeration . class .getResourceAsStream( "testPropertiesPath1.properties" ); InputStream ips3 = Enumeration . class .getResourceAsStream( "properties/testPropertiesPath2.properties" );

G. 如何在java类中读取Properties配置文件

最常用读取properties文件的方法 InputStream in = getClass().getResourceAsStream("资源Name");这种方式要求properties文件和当前类在同一文件夹下面。如果在不同的包中,必须使用: InputStream ins = this.getClass().getResourceAsStream(

H. 封装JDBC工具类解析XML获取配置中的数据库信息

packagetool;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importjava.util.HashMap;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importjavax.xml.parsers.ParserConfigurationException;importorg.w3c.dom.Element;importorg.w3c.dom.Node;importorg.w3c.dom.NodeList;importorg.xml.sax.SAXException;publicclassJdbcXmlParse{/**数据库配置信息*/privatestaticHashMap<String,JdbcBean>beanMap;(StringdbName){if(beanMap==null){//配置文件路径Stringpath=System.getProperty("user.dir")+File.separator+"src/tool/dbConfig.xml";try{newJdbcXmlParse().initDbconfig(path);}catch(Exceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}returnbeanMap.get(dbName);}privatevoidinitDbconfig(StringdbCfgPath),SAXException,IOException{//初始化mapbeanMap=newHashMap<String,JdbcBean>();DocumentBuilderdombuilder=DocumentBuilderFactory.newInstance().newDocumentBuilder();InputStreamis=newFileInputStream(dbCfgPath);Elementroot=dombuilder.parse(is).getDocumentElement();NodeListchilds=root.getChildNodes();for(inti=0;i<childs.getLength();i++){Nodechild=childs.item(i);if("db".equals(child.getNodeName())){//数据库种类StringdbType=child.getAttributes().getNamedItem("type").getTextContent();JdbcBeanbean=newJdbcBean();//读取一个数据库的配置信息NodeListdbNode=child.getChildNodes();for(intj=0;j<dbNode.getLength();j++){NodeaChild=dbNode.item(j);if(aChild.getNodeName().equals("driveName")){bean.setDriveName(aChild.getTextContent());}elseif(aChild.getNodeName().equals("username")){bean.setUsername(aChild.getTextContent());}elseif(aChild.getNodeName().equals("password")){bean.setPassword(aChild.getTextContent());}elseif(aChild.getNodeName().equals("url")){bean.setUrl(aChild.getTextContent());}}beanMap.put(dbType,bean);}}}}packagetool;/***@author月光雪松*数据库连接Bean*/publicclassJdbcBean{/**驱动名称*/privateStringdriveName;/**用户名*/privateStringusername;/**密码*/privateStringpassword;/**连接地址*/privateStringurl;publicStringgetDriveName(){returndriveName;}publicvoidsetDriveName(StringdriveName){this.driveName=driveName;}publicStringgetUsername(){returnusername;}publicvoidsetUsername(Stringusername){this.username=username;}publicStringgetPassword(){returnpassword;}publicvoidsetPassword(Stringpassword){this.password=password;}publicStringgetUrl(){returnurl;}publicvoidsetUrl(Stringurl){this.url=url;}}JbbcTool.java/***获取连接对象Connection*@return*@throwsClassNotFoundException*@throwsSQLException*/()throwsClassNotFoundException,SQLException{//作业1:以上4个临时变量,解析XML,赋值JdbcBeanjdbcBean=JdbcXmlParse.getJdbcBean("oracle");if(jdbcBean==null){returnnull;}StringdriveName=jdbcBean.getDriveName();Stringusername=jdbcBean.getUsername();Stringpassword=jdbcBean.getPassword();Stringurl=jdbcBean.getUrl();Class.forName(driveName);Connectioncn=DriverManager.getConnection(url,username,password);returncn;}

只做了xml读取,数据库连接取得,其他的楼主自己不上吧


赞 (0)