this.getClass().getClassLoader().getResource();

通过相对路径来加载资源,读取当前文件夹路径。

getSystemResources

public static Enumeration<URL> getSystemResources(String name)
                                           throws IOException
Finds all resources of the specified name from the search path used to load classes. The resources thus found are returned as an  Enumeration of  URL objects.

The search order is described in the documentation for getSystemResource(String).

Parameters:
name - The resource name
Returns:
An enumeration of resource  URL objects
Throws:
IOException - If I/O errors occur
Since:
1.2

getSystemResourceAsStream

public static InputStream getSystemResourceAsStream(String name)
Open for reading, a resource of the specified name from the search path used to load classes. This method locates the resource through the system class loader (see  getSystemClassLoader()).

Parameters:
name - The resource name
Returns:
An input stream for reading the resource, or  null if the resource could not be found
Since:
1.1

===============================================================  

String path = this. getClass().getClassLoader().getResource("test.xml");

InputStream in = test.getClass().getClassLoader()
				.getResourceAsStream("test.xml");

===============================================================

The code below shows how it works

import java.io.InputStream;

public class TestClassloader {

	public static void main(String[] args) {

		System.out.println("========dynamic========");
		TestClassloader test = new TestClassloader();
		test.printInfo();
		System.out.println(test.getClass().getResource("test.xml"));
		System.out
				.println(test.getClass().getResource("TestClassloader.class"));
		InputStream in = test.getClass().getClassLoader()
				.getResourceAsStream("test.xml");

		System.out.println("========static========");
		System.out.println(TestClassloader.class.getClassLoader().getResource(
				"test.xml"));
		in = TestClassloader.class.getClassLoader().getResourceAsStream(
				"test.xml");
	}

	public void printInfo() {
		System.out.println(this.getClass().getResource("test.xml"));
	}
}

The console screen:

========dynamic========
file:/C:/Users/XXXX/workspaceForJava/TestXML_Parser/bin/test.xml
file:/C:/Users/XXXX/workspaceForJava/TestXML_Parser/bin/test.xml
file:/C:/Users/XXXX/workspaceForJava/TestXML_Parser/bin/TestClassloader.class
========static========
file:/C:/Users/XXXX/workspaceForJava/TestXML_Parser/bin/test.xml

=======================



参考资料:

http://xixinfei.iteye.com/blog/1256291

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html#getSystemClassLoader()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值