First look at an instance
| The code is as follows: |
Copy code |
|
// Obtain the absolute path of the object
Public static String realpath (Object obj) throws URISyntaxException {
Return new File (obj. getClass (). getResource (""). toURI (). getAbsolutePath ();
} |
In general, you do not need to directly use absolute paths. You can use streams. this. getClass (). getResourceAsStream (filename ).
To obtain the Project root path, replace obj. getClass () in the code with obj. getClass (). getClassLoader.
System. getProperty ("user. dir") is the current working directory of the user. This should be related to the environment. In eclipse, it is the upper-level directory of src.
Check the jdk api for other information.
| The code is as follows: |
Copy code |
|
/**
* The absolute path of the directory where the object is located, that is, the absolute path of the package
*
* @ Param obj
* Object
*
* @ Return String
*/
Public static String getClassPath (Object obj) throws URISyntaxException {
Return new File (obj. getClass (). getResource (""). toURI ())
. GetAbsolutePath ();
}
/**
* Obtain the root path (absolute path) of the current project)
*
* @ Param obj
* Object
*
* @ Return String
*/
Public static String getProjectPath (Object obj) throws URISyntaxException {
Return new File (obj. getClass (). getClassLoader (). getResource (""). toURI ())
. GetAbsolutePath ();
} |
If an absolute path in the project is obtained
Generally, request. getRealPath ("/") or request. getRealPath ("/config /")
However, we do not recommend using request. getRealPath ("/"). You can use the ServletContext. getRealPath ("/") method to obtain the absolute path of the root directory of the Web application.
It is very easy to obtain src files, because src is the default relative directory. For example, if you want to obtain the test. java file in the com directory under src, you only need to do this.
| The code is as follows: |
Copy code |
|
File f = new File (com/test. java ); |
But what if I want to retrieve files not in the src or WebRoot directory, but from directories at the same level as src or WebRoot, for example, doc. My hard method is implemented as follows:
| The code is as follows: |
Copy code |
|
String path = this. getServletContext (). getRealPath ("/");
Properties p = new Properties ();
P. load (new FileInputStream (new File (path. substring (0, (path. lastIndexOf ("// WebRoot") + 1) + "doc/db. properties ")));
System. out. println (p. getProperty ("driverName ")); |