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 ("/"); |