Several common ways to get files in Java

Source: Internet
Author: User

1, User.dir

System. out. println (System. GetProperty("User.dir"));

This party gets the running path

Like what

1.

2. If running on Eclipse is the eclipse run file sibling

3. Tomcat is in

4. File File = new file ("Log4j.properties");

The log4j.properties is also located in the category above.

5, Fileinputstreaminput = newfileinputstream ("log4j.properties");

As with file, find files on the run path

2. Get the absolute path

Method String in = Logutil. class. GetResource ("/"). GetPath ();

Or:this. getclass (). getClassLoader (). GetResource ("/"). GetPath ()

Results:

/e:/temp/springmvc/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/rentbook/web-inf/classes/

Logutil. class. GetResource ("/"). GetPath (); Add a "/" to print the absolute path under classes

Logutil. class. GetResource (""). GetPath (); The classes + package name will be displayed

Tomcat prints as follows:

Web Engineering

this. Getservletcontext (). Getrealpath ("/")

Return:

The absolute path/return of the project is also known as the "root"

such as engineering:

Book

|_web-inf

|_xx.properties

Back to D:\Book\

3. Relative path:

InputStream input = Logutil. class. getResourceAsStream ("/log4j.properties");

Read the file under Src/log4j.properties

and

InputStream input = Logutil. class. getResourceAsStream ("log4j.properties");

Reading is log4j.properties with Logutil peers.

The second type:

Getservletconfig (). Getservletcontext ()
. getResourceAsStream ("Report1.jasper")

The root path is accessed

Book

|_web-inf

|_xx.properties

|_report1.jasper

Several common ways to get files in Java

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.