---
title: "获取资源文件的数据Properties"
author: "413899327"
date: "2010-08-14T16:33:32Z"
tags: []
categories: ["编程语言"]
slug: "properties"
draft: false
lastmod: "2010-08-14T16:33:32Z"
id: 737388
url: "https://rogerfederer.iteye.com/blog/737388"
---

```java
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();
	}

}
```


配置文件：

```java
ipConfig.properties
ip=192.168.0.1    
port=8080 
```


结果：

```java
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


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

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

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

```


以上2中写法都会抛
<span style="color:red">Exception in thread "main" java.lang.NullPointerException</span>