Acquisition of absolute and relative paths in Java RCP

Source: Internet
Author: User
Tags code tag parent directory

1. Understanding of Basic concepts

Absolute path: Absolute path is the true path of the file or directory on your home page on your hard disk, (URL and physical path) For example: C:/xyz/est.txt represents the absolute path of the Test.txt file. Http://www.sun.com/index.htm also represents a URL absolute path.

Relative path: The path relative to a base directory. Contains the relative path of the web (relative directories in HTML), for example: In a servlet, "/" represents the directory for Web applications, and the relative representation of the physical path. For example: "./" represents the current directory, "... /"represents the parent directory. This similar representation is also a relative path.



2. About relative and absolute paths in Jsp/servlet
2.1, server-side address

The relative address on the server side refers to the address of your Web application, which is resolved on the server side (unlike the relative addresses in HTML and JavaScript, They are parsed by the client browser, which means that the relative address in the JSP and servlet at this time should be relative to your Web application, that is, relative to http://192.168.0.1/webapp/.

The places it uses are:
Forward:servlet in Request.getrequestdispatcher (address); This address is resolved on the server side, so you have to forward to A.jsp should write this: Request.getrequestdispatcher ("/user/a.jsp") this/relative to the current Web application WebApp, its absolute address is: http://192.168.0.1/webapp/user/a.jsp. Sendredirect: <%response.sendredirect in JSP ("/rtccp/user/a.jsp");%>
2.2, the client's address

The relative addresses in all HTML pages are relative to the server root (HTTP://192.168.0.1/) rather than to the directory of the Web application (in the directory) http://192.168.0.1/webapp/. The address of the form's action attribute in HTML should be relative to the server root (HTTP://192.168.0.1/), so if you commit to a.jsp as: action= "/webapp/user/a.jsp" or "action=" <%=request.getcontextpath ()% > "/user/a.jsp;
Submitting to the servlet for actiom= "/webapp/handleservlet" JavaScript is also resolved on the client side, so its relative path is the same as the form form. Therefore, in general, in the Jsp/html page, such as the reference css,javascript.action and other attributes, preferably preceded by <%=request.getcontextpath ()%> To ensure that the referenced files belong to a directory in the Web application. In addition, you should try to avoid using a similar ".", "./", ".. /.. /"A relative path relative to the location of the file, so that when the file is moved, it can easily go wrong.

The relative and absolute paths of the current application are obtained in the 3.jsp/servlet

3.1, in the JSP to obtain the current application of the relative path and absolute path:

Absolute path for root directory: Request.getrequesturi ()

Absolute path of the file: Application.getrealpath (Request.getrequesturi ());

Absolute path to the current Web application: Application.getrealpath ("/");

Gets the upper directory of the request file:

New File (Application.getrealpath (Request.getrequesturi ())). GetParent ()
3.2, the servlet to obtain the current application of the relative path and absolute path

The absolute path of the root directory: Request.getservletpath ();

Absolute path of File:

Request.getsession (). Getservletcontext (). Getrealpath (Request.getrequesturi ())

Absolute path of the current Web application: Servletconfig.getservletcontext (). Getrealpath ("/");
(ServletContext objects get several ways:
Javax.servlet.http.HttpSession.getServletContext ()
Javax.servlet.jsp.PageContext.getServletContext ()
Javax.servlet.ServletConfig.getServletContext ()
)

4. Use relative paths in the page

1 For example, now there is a page "index.htm", in which the link has a picture "photo.jpg". Their absolute path is as follows:



①c:/website/index.htm
C:/website/img/photo.jpg

If you use the absolute path "c:/website/img/photo.jpg", then everything works on your own computer because you can actually find the "photo.jpg" file in the specified location, "c:/website/img/photo.jpg." But when you upload the page to the site, it's probably going to go wrong. Because your site may be in the server "C" disk, may be in the "D" disk, may also be in the "AA" directory, more likely in the "BB" directory, in short, there is no reason for "c:/website/img/photo.jpg" Such a path. So, what path do you want to use in the "index.htm" file to locate the "photo.jpg" file? Yes, it should be a relative path, the so-called relative path, as the name suggests is their relative and target position. The "Photo.jpg" joined in "index.htm" in the example above can use "img/photo.jpg" to locate files, so no matter where they are placed, there is no error as long as their relative relationship does not change.

In addition we use ".. /"to represent the previous level of the directory,".. /.. /"represents the directory on the ancestor, and so on. (A friend who has studied "DOS" may be easier to understand)

To take a look at a few more examples, note that all of the examples in the "index.htm" file are joined with a picture "photo.jpg".



②c:/website/web/index.htm
C:/website/img/photo.jpg

How should "Photo.jpg" in "index.htm" in this example be represented?

Wrong wording: img/photo.jpg

This writing is not correct, in this case, for "index.htm" file, "Img/photo.jpg" represents the absolute path is "c:/website/web/img/photo.jpg", obviously does not meet the requirements.

Correct wording: use ".. /img/photo.jpg the relative path to locate the file



③c:/website/web/xz/index.htm
C:/website/img/images/photo.jpg

How should "Photo.jpg" in "index.htm" in this example be represented?

Wrong wording:. /img/images/photo.jpg

This type of writing is incorrect, in this case, for the "index.htm" file. The absolute path represented by "/img/images/photo.jpg" is "c:/website/web/img/images/photo.jpg".

The correct wording: You can use the ".. /.. /img/images/photo.jpg the relative path to locate the file

④c:/website/web/xz/index.htm
C:/website/web/img/photo.jpg

How should "Photo.jpg" in "index.htm" in this example be represented?

Wrong wording:. /.. /img/photo.jpg

This type of writing is incorrect, in this case, for the "index.htm" file. /.. The absolute path represented by "/img/photo.jpg" is "c:/website/img/photo.jpg".

The correct wording: You can use the ".. /img/photo.jpg the relative path to locate the file

Summary: Through the above examples can be found, in the absolute path to the relative path, two files absolute path of the same part can be ignored, do not consider. Just think about what they are different.

2 How to modify the path of the style sheet:

Open the "htm" file using a text editor, view the source code, and locate the "<link rel=" stylesheet "href=" in the beginning of the source code, "The
Cases:
C:/website/web/xz/index.htm
C:/website/css/test.css

In this example, the join "test.css" file in "index.htm", you can use the ".. /.. /css/test.css "The relative path to locate the file, the complete code tag is" <link rel= "stylesheet" href= ". /.. /css/test.css "type=" Text/css ">"

Error writing examples:.. /.. /.. /css/test.css

This type of writing is incorrect, in this case, for the "index.htm" file. /.. /.. /css/test.css "is the absolute path represented by" C:/css/test.css "

Finally, to avoid a path error when making a Web page, we can use the Dreamweaver site management feature to manage the site. As long as you use the menu command "site>new site > New site" To create a new site and define the site directory, it will automatically convert the absolute path to a relative path, and when you move files in the site, the connection path associated with those files will automatically change, It's really very convenient.



The method of obtaining the relative path and absolute path in the class of 5.java
5.1. Get absolute paths in separate Java classes
According to Java.io.File's doc block, we know:
By default, the directory represented by new File ("/") is: System.getproperty ("User.dir").
The following program obtains the current path of the execution class

Package org.cheng.file;

Import Java.io.File;

public class filetest ... {
public static void Main (string[] args) throws Exception ... {
System.out.println (Thread.CurrentThread (). Getcontextclassloader (). GetResource (""));

System.out.println (FileTest.class.getClassLoader (). GetResource (""));

System.out.println (Classloader.getsystemresource (""));
System.out.println (FileTest.class.getResource (""));
System.out.println (FileTest.class.getResource ("/"));
The path where the class file resides
System.out.println (New File ("/"). GetAbsolutePath ());
System.out.println (System.getproperty ("User.dir"));
}
}

5.2, the Java class in the server to get the current path
(1). Weblogic
The WebApplication system file root directory is the root directory where your WebLogic installation resides.
For example: If your WebLogic is installed in c:/beaweblogic700 ...
So, your file root path is C:.
So there are two ways that you can access your server-side files:
A. Use absolute paths:
Like putting your parameter file in C:yourconfigyourconf.properties,
Direct use of new FileInputStream ("Yourconfig/yourconf.properties");
B. Use relative paths:
The root directory of the relative path is the root path of your webapplication, the Web-inf directory, where you put your parameter file in Yourwebappyourconfigyourconf.properties,
Use this:
New FileInputStream ("./yourconfig/yourconf.properties");
Both of these options are available to you.
(2). Tomcat

Output System.getproperty ("User.dir") in the class;%tomcat_home%/bin is displayed.
(3). Resin

Not your JSP put the relative path, is the JSP engine to execute this JSP compiled into a servlet
The path to the root. For example, to test the file F = new file ("A.htm") with the new document method;
This a.htm is under the resin installation directory.
(4). How to read relative paths.

GetResource or getResourceAsStream in a Java file can be

Example: GetClass (). getResourceAsStream (FilePath);//filepath can be "/filename", where/on behalf of the Web publishing root path web-inf/classes

The default path for using this method is: web-inf/classes. has been tested in Tomcat.


6. Read the file relative path, to avoid the use of hard coding and absolute path
6.1, the use of Spring di mechanism to obtain files to avoid hard coding.
Refer to the following connection content:
http://www.javajia.net/viewtopic.php?p=90213&
6.2, the configuration file read
Refer to the following connection content:
Http://dev.csdn.net/develop/article/39/39681.shtm
6.3, through the virtual path or relative path to read an XML file, to avoid hard coding
Refer to the following connection content:
Http://club.gamvan.com/club/clubPage.jsp?iPage=1&tID=10708&ccID=8

7.Java common operations for files (copy, move, delete, create, etc.)
Common Java File Action classes
Http://www.easydone.cn/014/200604022353065155.htm

Java File Operations Encyclopedia (in JSP)
Http://www.pconline.com.cn/pcedu/empolder/gj/java/0502/559401.html

Java file Operations Detailed (Java Chinese network)
Http://www.51cto.com/html/2005/1108/10947.htm

JAVA How to create delete modify copy directory and file
Http://www.gamvan.com/developer/java/2005/2/264.html

Summarize:
Through the use of the above content, you can solve the Web application server side, mobile files, find files, copy
Delete files and other operations, at the same time, the relative address of the server, absolute address concept more clearly.
Recommended reference URI, the RFC standard text block. and understand the contents of Java.io.File Java.net.URI.
Other aspects of the understanding can be more in-depth and thorough.



This is the way to get the root directory of the current project in Java

Java code


public class application ... {


public static String Getrootpath () ... {
Because the class name is "Application", therefore "application.class" must be able to find
String result = Application.class.getResource ("Application.class"). ToString ();
int index = Result.indexof ("Web-inf");
if (index = = 1) ... {
index = Result.indexof ("bin");
}
result = Result.substring (0,index);
if (Result.startswith ("jar")) ... {
When the class file is in the jar file, return the "jar:file:/f:/" kind of Path
result = Result.substring (10);
}else if (result.startswith ("file")) ... {
Returns the "file:/f:/..." path when the class file is in the class file
result = result.substring (6);
}
if (Result.endswith ("/")) result = Result.substring (0,result.length ()-1);//does not contain the last "/"
return result;
}
}

8. To get the file path from the plugin/RCP

1 get absolute path from plugin:
Aaaaplugin.getdefault (). Getstatelocation (). Makeabsolute (). ToFile (). GetAbsolutePath ());

Get project by file:
Iproject project = ((ifile) O). Getproject ();

2 through the file to get the full path:
①string Path = ((IFile) O). GetLocation (). Makeabsolute (). ToFile (). GetAbsolutePath ();

②ifolder Srcfolder =

Resourcesplugin.getplugin (). Getworkspace (). Getroot (). Getproject (

"Yourprojectname"). GetFolder ("src");
IFile ifile = Srcfolder.getfile ("Hibernate.cfg.xml");

String path= ifile.getlocation (). Makeabsolute (). ToFile (). GetAbsolutePath ();
Where path gets the true absolute path.

3) Get the root of the whole workspace:
Iworkspaceroot root = Resourcesplugin.getworkspace (). Getroot ();

4 to find resources from the root:
Iresource resource = Root.findmember (new Path (containername));

5 from bundle to find resources:
Bundle Bundle = Platform.getbundle (pluginID);
URL fullpathstring = Bundleutility.find (bundle, FilePath);

6) Get Appliaction workspace:
Platform.aslocalurl (

Product_bundle.getentry ("")). GetPath ()). GetAbsolutePath ();

7) Get Runtimeworkspace:
Platform.getinstancelocation (). GetURL (). GetPath ();

8 from the editor to get the edit file:
Ieditorpart editor = (defaulteditdomain) (Parent.getviewer (). Geteditdomain ())). Geteditorpart ();
Ieditorinput input = Editor.geteditorinput ();
if (input instanceof ifileeditorinput) {
IFile file = ((ifileeditorinput) input). GetFile ();
}



9 Get the absolute path of the project:
Filelocator.tofileurl (

Platform.getbundle (application.plugin_id). Getentry ("")). GetPath ()



10 If your RCP project is not published, you get the eclipse path. If your RCP project has been released (if under d:/rcp/), the resulting path is d:/rcp/.

Location Installloc = Locationmanager.getinstalllocation ();
String path = null;
String InstallPath = null;
if (Installloc!= null)
{

URL InstallUrl = Installloc.geturl ();
Assume install URL is file:based
Path = Installurl.getpath ();
}

InstallPath = path.substring (1, Path.length ());

11 the method of displaying the image of the relative path. As follows:

①imagedescriptor imagedes =

Abstractuiplugin.imagedescriptorfromplugin (application.plugin_id, "/images/schemabase.jpg");

Image image = Imagedes.createimage ();

②put a class in image directory.
For instance:
.. /.. /resource/icon1.bmp
.. /.. /resource/resource.class

InputStream istream = Resources.class.getResourceAsStream ("Icon1.bmp");
Image icon_image = new Image (Display.getcurrent (), IStream);



12 method to get plugin root directory path
public static string Getroot (String pluginID) {
String Path=null;
try {
Path = Filelocator.tofileurl (
Platform.getbundle (pluginID). Getentry ("")). GetPath ();
Path = path.substring (Path.indexof ("/") + 1, path.length ());
catch (Exception e) {
E.printstacktrace ();
}
return path;
}



Eclipse 3.1.1 later used by:
URL Bundlerooturl = Yourplugin.getdefault (). Getbundle ()
. Getentry ("/");
try {
URL Pluginurl = Platform.resolve (Bundlerooturl);
return Pluginurl.getpath ();
catch (IOException e) {

}

where the URL Pluginurl = platform.resolve (Bundlerooturl);
Eclipse 3.2M6 recommends replacing platform.resolve with Filelocator#resolve (URL)

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.