Getresourceasstream: searches for resources with a given name. Return inputstreamgetresource: Find the resource path with the given name. Return URL
Simple Example: (Note: any class has a getclass () method)
Public class test {
Public void getresource (string URL ){
Inputstream stream = getclass (). getresourceasstream (URL );
System. Out. println (getclass (). getresource (URL ));
Byte [] line = new byte [1024*1024];
Try {
Stream. Read (line );
} Catch (ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
String STR = new string (line );
System. Out. println (Str. Trim ());
}
Public static void main (string [] ARGs ){
New Test (). getresource ("/IO/aaa.txt ");
}
}
Running result:
File:/D:/IBM/workspace/htmlparser/IO/aaa.txt
Abceefghijklmn
The first line is the content of aaa.txt, and the second line is the content of aaa.txt.
Note that the preceding "/" must exist, which indicates the project directory. Otherwise, the project directory cannot be found.
1. in the init method of servlet, string Path = getservletcontext (). getrealpath ("/"); this will obtain the full path of the web project, for example, E:/eclipsem9/workspace/tree/is the root directory of my web project 2. you can also call this in any class at any time. getclass (). getclassloader (). getresource ("/"). getpath (); this will get the full path of the classes directory such as: e:/eclipsem9/workspace/tree/WEB-INF/classes/this method can also determine the path in the web environment, relatively easy to use 3. request. getcontextpath (); obtain the context of the web root. For example,/treetree is the root context of my web project.