Getresourceasstream and getresource usage

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.