ITeye博客

获取资源文件的数据Properties

413899327 · 2010-08-14 16:33 · java总结 · 编程语言 · Markdown

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class SpringClassTest {

	// ip=192.168.0.1
	// port=8080

	public SpringClassTest() {
		super();
	}

	public void read() throws IOException {
		Properties p = new Properties();

		System.out.println("this.getClass():" + this.getClass()
				+ "\nthis.getClass().getClassLoader():"
				+ this.getClass().getClassLoader().toString());

		InputStream inputStream = this.getClass().getClassLoader()
				.getResourceAsStream("ipConfig.properties");

		p.load(inputStream);

		inputStream.close();

		System.out.println("ip:" + p.getProperty("ip") + ",port:"
				+ p.getProperty("port"));

	}

	public static void main(String[] args) throws IOException {
		new SpringClassTest().read();
	}

}

配置文件:

ipConfig.properties
ip=192.168.0.1    
port=8080 

结果:

this.getClass():class com.kettas.spring.test.SpringClassTest
this.getClass().getClassLoader():sun.misc.Launcher$AppClassLoader@19821f
ip:192.168.0.1    ,port:8080 

2中错误写法:

第一种加上了“/”---->/ipConfig.properties

InputStream inputStream = this.getClass().getClassLoader()
				.getResourceAsStream("/ipConfig.properties");

第二种是写据对路径--->D:\Workspaces\MyEclipse 6.5\components\src\com\spring\test\ipConfig.properties

InputStream inputStream = this.getClass().getClassLoader()
				.getResourceAsStream("D:\\Workspaces\\MyEclipse 6.5\\components\\src\\com\\spring\\test\\ipConfig.properties");

以上2中写法都会抛 Exception in thread "main" java.lang.NullPointerException

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。