Two ways to get the absolute path of a project from Java class

Source: Internet
Author: User

You will often encounter problems with getting the project path through the Java class and loading the resource file through that relative path or absolute path. The two most commonly used methods are the GetResource () method of the ClassLoader or class.

public static final String GetPath () {String path1 = Constant.class.getClassLoader (). GetResource (""). GetPath (); String path2 = Constant.class.getClassLoader (). GetResource ("/"). GetPath (); String path3 = Constant.class.getResource (""). GetPath (); String Path4 = Constant.class.getResource ("/"). GetPath (); System.out.println (path1); System.out.println (path2); System.out.println (PATH3); System.out.println (PATH4); return path1;}

Through the printed result of the code, it can be judged that PATH1,PATH2,PATH3 is the classpath path of the project, and Path3 is the classpath path of the class.

Get to the project's classpath path, you can manipulate the project's various resource files, you can also add folders or files in the path's upper-level path.

Of course, for Web projects have their own methods, get the project path, as follows

Request.getsession (). Getservletcontext (). Getrealpath ("/xx");


Two ways to get the absolute path of a project from Java class

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.