通过相对路径来加载资源,读取当前文件夹路径。
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
ofURL
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()