Java obtains the current path and absolute path code

Source: Internet
Author: User

There are many function files in java that obtain the current path and the absolute path. I will introduce you to the usage of related functions in detail. If you need them, refer to them.

Current path

1. Use the System. getProperty () function to obtain the current path:

The Code is as follows: Copy code

System. out. println (System. getProperty ("user. dir"); // user. dir specifies the current path.

2. Use the function provided by File to obtain the current path:

The Code is as follows: Copy code

File directory = new File (""); // set it to the current folder
Try {
System. out. println (directory. getCanonicalPath (); // obtain the standard path.
System. out. println (directory. getAbsolutePath (); // obtain the absolute path.
} Catch (shorttin e ){}

Absolute path

The following methods are generally used to obtain absolute paths in JAVA:

The Code is as follows: Copy code

Request. getRealPath () // This method has expired and is not recommended.

This. getServletContext (). getRealPath () // used in SERVLET

This. getServlet (). getServletContext (). getRealPath () // used in Struts

Request. getSession (). getServletContext (). getRealPath ()


The obtained is the absolute URI path of the current classpath.

The Code is as follows: Copy code

Test. class. getResource ("/")

Obtain the true file path

The Code is as follows: Copy code

String file_real_path = ServletContext. getRealPath ("mypath/filename ");?
Request. getRealPath ("/") is not recommended ("/");

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.