读取资源文件信息

it2026-04-23  10

读取资源文件

摘要:对资源文件.properties的读写操作

一. 获取类路径的方式:

获取某个类的位置(编译后的.class文件的位置): new Junit().getClass().getResource("").getPath();

获取classpath的位置(在tomcat中完美获取,在weblogic中无法正常获取,在JavaApplication中也能获取):

this.getClass().getResource("").getPath();

获取classpath的位置(该方法在jdk7以后无效):

Thread.currentThread().getContextClassLoader(). getResource("").getPath();

二. Properties 类

Properties类主要是对资源文件进行读写操作 它提供了几个主要的方法:

getProperty ( String key) 用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。

load ( InputStream inStream) 从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。

setProperty ( String key, String value) 调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。

store ( OutputStream out, String comments) 以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

clear 清除所有装载的 键 - 值对。该方法在基类中提供。

读取资源文件的代码如下:

public void getProperties(){ // demo 中获取的资源文件都是放在src下面的,即都会被编译到 classpath 下 // 如果 properties 文件不放在 classpath 下,使用绝对路径也不能取到文件, 这一点还需要再研究下, // 可以用BufferedInputStream(inputStream)方法尝试下 // 在 getResourceAsStream 中的参数以 "/" 开头,则获取到的是 classpath, 获取资源文件需要自己写上包名, 如代码1 // 如果参数直接写资源文件的文件名, 则表示资源文件与该类在同一个目录下, 如代码2 // 如果把获取资源文件作为静态方法, 那么该方法中无法使用对象 this // 为了在在静态方法中获取资源文件,可以使用 Obejct.class 来获取一个 Class 对象, 如代码3 // getResourceAsStream 只是需要一个 Class 对象, 用 int.class 照样行 InputStream inputStream = this.getClass().getResourceAsStream("/properties/param.properties"); //代码1 资源文件与类不在同一个包中 /* InputStream inputStream = this.getClass().getResourceAsStream("aram.properties"); //代码2 资源文件与类在同一个包中 InputStream inputStream = Object.class.getResourceAsStream("aram.properties"); // 代码3 如果当前类是个静态方法,则不能使用代码2,要把this 换成 Object.class() */ Properties properties = new Properties(); try { properties.load(inputStream); // 把获取的资源文件加载到 Proeprties 类中,然后可以通过 getProperty("key") 获取属性的值 Enumeration enumeration = properties.propertyNames(); // 获取资源文件中的属性 while(enumeration.hasMoreElements()){ String paramName = enumeration.nextElement().toString(); System.out.println("资源文件中的参数名:" + paramName); } } catch (IOException e) { e.printStackTrace(); } }

写入资源文件的代码如下:

todo

转载于:https://www.cnblogs.com/jinxiuze/p/8127140.html

相关资源:JAVA100例之实例89数据库连接从属性文件中获得
最新回复(0)