If eclipse or other. class files are not packaged, use the following statement to obtain the absolute path of the. Class file:
String classFilePath = clazz.class.getResource("").getPath();
When the. Class file is imported into the jar package, the above statement will report an error. In this case, you can obtain the absolute path of the JAR file where the. Class file is located:
String jarFilePath = clazz.class.getProtectionDomain().getCodeSource().getLocation().getFile(); jarFilePath = java.net.URLDecoder.decode(jarFilePath, "UTF-8");
JSP:
String slocalrealpath = application. getrealpath ("/"). Replace ('\', '/'); If (slocalrealpath! = NULL &&! Slocalrealpath. endswith ("/") {slocalrealpath. Concat ("/"); // avoid inconsistency between Weblogic and WebSphere}
Java:
String sclassrealpath = new string (""); // The first will return a more "/", such as/D:/test/WEB-INF/, strange, so use substring () sclassrealpath = This. getclass (). getresource ("/"). getpath (). substring (1 ). replaceall ("//", "/"); system. out. println (sclassrealpath );
1. How to obtain the current file path
Frequently used:
(1). Test. Class. getresource ("")
The URI Directory of the current filetest. Class file is obtained. Not yourself!
(2). Test. Class. getresource ("/")
Obtain the absolute URI path of the current classpath.
(3). thread. currentthread (). getcontextclassloader (). getresource ("")
The obtained absolute URI path of the current classpath.
(4). Test. Class. getclassloader (). getresource ("")
The obtained absolute URI path of the current classpath.
(5). classloader. getsystemresource ("")
The obtained absolute URI path of the current classpath.
Try not to use the relative path relative to the current user directory of system. getproperty ("user. dir"). We can see that the results are varied later.
(6) New file (""). getabsolutepath () is also available.
2. Web Server
(1). Tomcat
Output System. getproperty ("user. dir") in the class; % atat_home %/bin
(2). Resin
It is not the relative path of your JSP, but the JSP Engine executes this JSP to compile it into a Servlet
For example, use the new file method to test file F = new file ("a.htm ");
This a.htm is in the resin installation directory.
(3). How to read files
Use servletcontext. getresourceasstream ().
(4). Obtain the real path of the file
String file_real_path = servletcontext. getrealpath ("mypath/FILENAME ");?
Request. getrealpath ("/") is not recommended ("/");
3. File Operation class, which is not recommended. You can use the commons Io class.