1. Create a new Java project;
2, a new test package under the Src/main/java;
3. Create a new Test.java file and file.txt file under the test package;
4, Test.java file content is written as follows:
Package test; Import Java.net.URL; Public class Test { publicstaticvoid main (string[] args) { = Test. class. GetResource ("file.txt"); System.out.println (URL); = Thread.CurrentThread (). Getcontextclassloader (). GetResource ("Test/file.txt"); System.out.println (URL);} }
The print result is the absolute path to the file.txt file, as follows:
file:/users/lay-mac/desktop/svn/ali-mine/web/chapter3/target/classes/test/file.txtfile:/Users/lay-mac /desktop/svn/ali-mine/web/chapter3/target/classes/test/file.txt
We have seen the two methods of calling GetResource:
1) Class Call
This method of invocation can be understood as relative to the location of the Test.class file
file:/users/lay-mac/desktop/svn/ali-mine/web/chapter3/target/classes/test/
Stitching on
File.txt
2) ClassLoader Call
The class loader invocation method can be understood as relative to the location of the classpath:
file:/users/lay-mac/desktop/svn/ali-mine/web/chapter3/target/classes/
Stitching on
Test/file.txt
Note: Both file.txt and text/file.txt cannot be preceded by "/", which will not be found to return null
Java GetResource two ways to use