读取java配置文件|java web工程读取配置文件路径问题

⑴ java零配置读取配置文件

packageresources;importjava.io.IOException;importjava.io.InputStream;importjava.sql.Connection;importjava.sql.Driver;importjava.sql.SQLException;importjava.util.Properties;publicclassDbUtil{(){StringdriverClass=null;StringjdbcUrl=null;Stringuser=null;Stringpassword=null;//读取类路径下的jdbc.properties文件,我的配置文件放在src包下InputStreamin=DbUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");Propertiesproperties=newProperties();try{properties.load(in);}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}driverClass=properties.getProperty("driver");jdbcUrl=properties.getProperty("jdbcUrl");user=properties.getProperty("username");password=properties.getProperty("password");Driverdriver=null;try{driver=(Driver)Class.forName(driverClass).newInstance();}catch(InstantiationExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}catch(IllegalAccessExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}catch(ClassNotFoundExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}Propertiesinfo=newProperties();info.put("user",user);info.put("password",password);//通过Driver的connect方法获取数据库连接.Connectionconnection=null;try{connection=driver.connect(jdbcUrl,info);}catch(SQLExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}System.out.println("—-Thedatabaseisconnected—-");returnconnection;}}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:orclusername=cp2password=cp2test//调用方法publicstaticvoidmain(String[]args){Stringid="111111";Stringgread="3";List<Student>sList=newArrayList<Student>();Connectioncon=DbUtilCR.getConnection();PreparedStatementpre=null;ResultSetresult=null;Stringsql="selects.name,s.agefromstudentswheres.id=?ands.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()){Studentst=newStudent();st.setName(result.getString("name"));//与查询出的字段或者别名保持一致st.setAge(result.getString("age"));sList.add(st);}}catch(SQLExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}for(inti=0;i<sList.size();i++){System.out.println("姓名:"+sList.get(i).getName()+" 年龄:"+sList.get(i).getAge());}}

⑵ 用java 如何读取配置文件(如:资源文件)中配

java读取配置文件的几种方法如下:方式一:采用ServletContext读取,读取配置文件的realpath,然后通过文件流读取出来。因为是用ServletContext读取文件路径,所以配置文件可以放入在web-info的classes目录中,也可以在应用层级及web-info的目录中。文件存放位置具体在eclipse工程中的表现是:可以放在src下面,也可放在web-info及webroot下面等。因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。缺点:不能在servlet外面应用读取配置信息。方式二:采用ResourceBundle类读取配置信息,优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。缺点:只能加载类classes下面的资源文件且只能读取.properties文件。方式三:采用ClassLoader方式进行读取配置信息优点是:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息缺点:只能加载类classes下面的资源文件。方法4 getResouceAsStreamXmlParserHandler.class.getResourceAsStream 与classloader不同使用的是当前类的相对路径

⑶ java web工程,读取配置文件路径问题

读取配置文件 , xxx.properties放在/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();

⑷ 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); 返回读取指定资源的输入流。资源的搜索路径是虚拟机的内置类加载器的路径。

⑸ 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();

⑹ Java中spring读取配置文件的几种方法

Java中spring读取配置文件的几种方法如下:一、读取xml配置文件 (一)新建一个java beanpackage chb.demo.vo;public class HelloBean { private String helloWorld; public String getHelloWorld() { return helloWorld; } public void setHelloWorld(String helloWorld) { this.helloWorld = helloWorld; }} (二)构造一个配置文件<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" ><beans> <bean id="helloBean" class="chb.demo.vo.HelloBean"> <property name="helloWorld"> <value>Hello!chb!</value> </property> </bean></beans> (三)读取xml文件 1.利用ApplicationContext context = new ("beanConfig.xml");//这种用法不够灵活,不建议使用。 HelloBean helloBean = (HelloBean)context.getBean("helloBean"); System.out.println(helloBean.getHelloWorld()); 2.利用FileSystemResource读取Resource rs = new FileSystemResource("D:/software/tomcat/webapps/springWebDemo/WEB-INF/classes/beanConfig.xml"); BeanFactory factory = new XmlBeanFactory(rs); HelloBean helloBean = (HelloBean)factory.getBean("helloBean"); System.out.println(helloBean.getHelloWorld()); 值得注意的是:利用FileSystemResource,则配置文件必须放在project直接目录下,或者写明绝对路径,否则就会抛出找不到文件的异常。 二、读取properties配置文件 这里介绍两种技术:利用spring读取properties 文件和利用java.util.Properties读取 (一)利用spring读取properties 文件 我们还利用上面的HelloBean.java文件,构造如下beanConfig.properties文件:helloBean.class=chb.demo.vo.HelloBeanhelloBean.helloWorld=Hello!chb! 属性文件中的"helloBean"名称即是Bean的别名设定,.class用于指定类来源。 然后利用org.springframework.beans.factory.support.来读取属性文件 BeanDefinitionRegistry reg = new DefaultListableBeanFactory(); reader = new (reg); reader.loadBeanDefinitions(new ClassPathResource("beanConfig.properties")); BeanFactory factory = (BeanFactory)reg; HelloBean helloBean = (HelloBean)factory.getBean("helloBean"); System.out.println(helloBean.getHelloWorld()); (二)利用java.util.Properties读取属性文件 比如,我们构造一个ipConfig.properties来保存服务器ip地址和端口,如:ip=192.168.0.1port=8080 则,我们可以用如下程序来获得服务器配置信息: InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ipConfig.properties"); Properties p = new Properties(); try { p.load(inputStream); } catch (IOException e1) { e1.printStackTrace(); }System.out.println("ip:"+p.getProperty("ip")+",port:"+p.getProperty("port")); 三 、用接口类WebApplicationContext来取。 private WebApplicationContext wac; wac =WebApplicationContextUtils.( this.getServletContext()); wac = WebApplicationContextUtils.getWebApplicationContext( this.getServletContext()); JdbcTemplate jdbcTemplate = (JdbcTemplate)ctx.getBean("jdbcTemplate");其中,jdbcTemplate为spring配置文件中的一个bean的id值。这种用法比较灵活,spring配置文件在web中配置启动后,该类会自动去找对应的bean,而不用再去指定配置文件的具体位置。

⑺ java代码中怎么读取配置文件

需要使用的是jar包:commons-collections-3.2.1.jar、commons-configuration-1.10.jar、commons-lang-2.6.jar和commons-logging-1.2.jar。可以读取的配置文件:xml和properties

⑻ java 中配置文件路径读取使用FileReader和InputStream区别和用法

一、按数据来源(去向)分类:1、是文件: FileInputStream, FileOutputStream, FileReader, FileWriter2、是byte[]:ByteArrayInputStream, ByteArrayOutputStream3、是Char[]: CharArrayReader, CharArrayWriter4、是String: StringBufferInputStream, StringReader, StringWriter5、网络数据流:InputStream, OutputStream, Reader, Writer二、按是否格式化输出分:1、要格式化输出:PrintStream, PrintWriter三、按是否要缓冲分:1、要缓冲:BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter四、按数据格式分:1、二进制格式(只要不能确定是纯文本的): InputStream, OutputStream及其所有带Stream结束的子类2、纯文本格式(含纯英文与汉字或其他编码方式);Reader, Writer及其所有带Reader, Writer的子类五、按输入输出分:1、输入:Reader, InputStream类型的子类2、输出:Writer, OutputStream类型的子类六、特殊需要:1、从Stream到Reader,Writer的转换类:InputStreamReader, OutputStreamWriter2、对象输入输出:ObjectInputStream, ObjectOutputStream3、进程间通信:PipeInputStream, PipeOutputStream, PipeReader, PipeWriter4、合并输入:SequenceInputStream5、更特殊的需要:PushbackInputStream, PushbackReader, LineNumberInputStream, LineNumberReader决定使用哪个类以及它的构造进程的一般准则如下(不考虑特殊需要):首先,考虑最原始的数据格式是什么: 原则四第二,是输入还是输出:原则五第三,是否需要转换流:原则六第1点第四,数据来源(去向)是什么:原则一第五,是否要缓冲:原则三 (特别注明:一定要注意的是readLine()是否有定义,有什么比read, write更特殊的输入或输出方法)第六,是否要格式化输出:原则二Java中Inputstream与Reader的区别Reader支持16位的Unicode字符输出,InputStream支持8位的字符输出。Reader和InputStream分别是I/O库提供的两套平行独立的等级机构,InputStream、OutputStream是用来处理8位元的流,Reader、Writer是用来处理16位元的流。而在JAVA语言中,byte类型是8位的,char类型是16位的,所以在处理中文的时候需要用Reader和Writer。值得说明的是,在这两种等级机构下,还有一道桥梁InputStreamReader、OutputStreamWriter负责进行InputStream到Reader的适配和由OutputStream到Writer的适配。java.io.Reader 和 java.io.InputStream 组成了 Java输入类。Reader 用于读入16位字符,也就是 Unicode编码的字符;而 InputStream 用于读入 ASCII字符和二进制数据。在 Java中,有不同类型的 Reader 输入流对应于不同的数据源:FileReader 用于从文件输入;CharArrayReader 用于从程序中的字符数组输入;StringReader 用于从程序中的字符串输入;PipedReader 用于读取从另一个线程中的 PipedWriter 写入管道的数据。相应的也有不同类型的 InputStream 输入流对应于不同的数据源:FileInputStream,ByteArrayInputStream,StringBufferInputStream,PipedInputStream。另外,还有两种没有对应 Reader 类型的 InputStream 输入流:Socket 用于套接字;URLConnection 用于 URL 连接。这两个类使用 getInputStream() 来读取数据。相应的,java.io.Writer 和 java.io.OutputStream 也有类似的区别。

⑼ java怎样提取配置文件!怎么才能采用ServletContext读取

创建配置文件:1、在项目的任意地方,右键-》New-》File-》FileName-》输入-》名称.properties(比如:config.properties)2、访问路径:从根目录开始出发(WebRoot)->WEB-INF->classes->config.properties,(如果有包名,在classes->包名->config.properties)(路径可以直接从本地中项目的路径,找到WEB-INF直接从地址中(比如我的本地磁盘保存是这样的:F:\课程\s2课程\s2书上内容\Java Web\ServletTest\WebRoot\WEB-INF\classes\config.properties))response.setContentType("text/html");response.setCharacterEncoding("utf-8");request.setCharacterEncoding("utf-8");PrintWriter out = response.getWriter();/************************使用servletContext.getResourceAsStream**************************************///实例化ServletContextServletContext servletContext=this.getServletContext();// //获取输入流// InputStream in=servletContext.getResourceAsStream("\\WEB-INF\\classes\\config.properties");// Properties p=new Properties();// //类的装载// p.load(in);// //拿到配置文件中userName参数// out.println(p.getProperty("userName"));/***************************普通的获取配置文件**************************************/String path= servletContext.getRealPath(("\\WEB-INF\\classes\\config.properties"));//拿到绝对路径FileInputStream in=new FileInputStream(path);Properties p=new Properties();p.load(in);out.println(p.get("userName"));


赞 (0)