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中错误写法:
[list]
[*]第一种加上了“/”---->/ipConfig.properties
[/list]
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("/ipConfig.properties");
[list]
[*]第二种是写据对路径--->D:\\Workspaces\\MyEclipse 6.5\\components\\src\\com\\spring\\test\\ipConfig.properties
[/list]
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("D:\\Workspaces\\MyEclipse 6.5\\components\\src\\com\\spring\\test\\ipConfig.properties");
以上2中写法都会抛
[color=red]Exception in thread "main" java.lang.NullPointerException[/color]