Collection of Java path Solutions

Source: Internet
Author: User

Space in Java path
1, TestURL (). class. getResource (""). getPath () or TestURL (). class. getResource (""). the Path obtained by getFile () cannot be directly applied by FileReader () and FileWriter.
The reason is that the URL encodes spaces, special characters (%, #, [], etc.), and Chinese characters.
For example, the space is changed to % 20.
Solution (1): After replacement with repaceAll ("% 20", ''), the space problem can only be solved. However, the path cannot contain % and Chinese characters.
Solution (2): Use URLDecoder. decode (str, "UTF-8") decoding, but can only solve a part, if the path contains +, is not resolved, because the URL is not completely using URLEncoder. encode (str, "UTF-8") encoded, after the + is decoded, it becomes a space.
Method (3) to solve all the problems. Use TestURL (). class. getResource (""). toURI (). getPath (), but the URISyntaxException must be handled.

Space in java path
If the path contains spaces
1. uri. getpath (); the space in the returned path still appears in the form of "space", such as/F:/MyEclipse Workspace/project/bin /...
In addition, spaces in all paths returned by the URL are displayed in the form of "% 20", and uri. toString () also appears in the form of "% 20.

2. new File (String filePath); accept parameters in the correct URI format and correct relative/absolute String path with "space" (not 20%, otherwise, the file cannot be found even if the given path is correct.

3. All the path delimiters returned by URLs and Uris are "/", and all the path delimiters returned by files are "\". For the path String returned by an existing file, all spaces appear as "spaces", while the new File from the nonexistent path, the space in the path returned by getPath () is still new file (String filePath) the original form of the parameter, that is, if the getPath () in filePath is a space, the returned space is still, "% 20" is still "% 20 ".

4. The new URL (); parameter can be a correct URI or a string in URI format. If the string is not in complete URI format, creation fails.

5. file. toURI () will convert the "space" in the path name of the file to "% 20", then add protocol: "file:/" before the path, and File. toURL () simply adds protocol: "file:/" before the file path, instead of converting "space" to "% 20 ", the original space and % 20 will be retained as they are!

6. In Woden, the implementation of WSDLReader. readWSDL (String s) must convert the parameter s into a URL. Therefore, there must be no space in the String parameter s, and it should be replaced by "20%. The parameter s is preferably a string in the standard URI format.
Java path Solution

Java paths are comparatively complicated. The latest work involves creating and reading files. The problems encountered in actual use are summarized as follows:
1. Explanation of relative paths
1. The relative path (relative path relative to the current user directory) can be obtained through the following methods (whether it is a general java project or a web Project)
String relativelyPath = System. getProperty ("user. dir ");
In general, files in java projects are relative to the root directory of the project, while in web projects, the file path may be a path of the server, at the same time, different web servers are also different (tomcat is relative to the tomcat installation directory \ bin ). Therefore, I personally think that in web projects, it is best not to use "relative paths relative to the current user directory ". However, by default, classes in the java. io package always analyze relative path names based on the current user directory. This directory is specified by the system property user. dir, which is usually the call Directory of the Java Virtual Machine. This means that when using classes in the java. io package, it is best not to use relative paths. Otherwise, although it may still be normal in the SE program, it may cause problems if it is difficult to get it in the EE program.
2. Relative Path to classpath
For example, the relative path relative to file:/D:/mywork/javaprj/MyTest/bin. Bin is the classpath of the project. All the. class files compiled from the Java source file are copied to this directory.
Class 2 Directory load (that is, obtain the directory when running a class)
1. For general java projects and web projects, first locate the level 1 directory where the package path is displayed.
InputStream is = ReadWrite. class. getClassLoader (). getResourceAsStream ("DeviceNO ");
The path of the DeviceNO file is project name \ src \ DeviceNO. The first-level directory of the class ReadWrite package is located in the src directory.
2. Similar to 1, the difference is that this method must start '/'.
InputStream is = ReadWrite. class. getResourceAsStream ("DeviceNO ");
The path of the DeviceNO file is project name \ src \ DeviceNO. The first-level directory of the class ReadWrite package is located in the src directory.
3. Obtain the root directory of the web Project
1. You can create a servlet and write the following statement in its init method:
ServletContext SC = this. getServletContext ();
String temp = SC. getRealPath ("/");
The output path is similar to "D: \ Apache \ Tomcat6.0 \ webapps \ windpower \" (windpower is the project name). If s1.getRealPath ("") is called ("") output "D: \ Apache \ Tomcat6.0 \ webapps \ windpower" (note that a "\" is missing at the end "\")
2. In httpServletRequest, you can use the following statement
String cp = request. getSession (). getServletContext (). getRealPath ("/"); the output path is similar to: "D: \ Apache \ Tomcat6.0 \ webapps \ windpower \"
Iv. Obtain the classpath (in Eclipse/MyEclipse, it is the path to obtain the src or classes directory)
Method 1. Thread. currentThread (). getContextClassLoader (). getResource (""). getPath ()
For example:
String path = Thread. currentThread (). getContextClassLoader (). getResource (""). getPath ();
System. out. println (path );
Print: '/D:/windpower/WebRoot/WEB-INF/classes /"
Method 2. ParsingXML. class. getClassLoader (). getResource (""). getPath () (ParsingXML is a class in a src package, the same below)
For example:
String path = ParsingXML. class. getClassLoader (). getResource (""). getPath ();
System. out. println ("ParsingXML. class. getClassLoader (). getResource --" + path );
Print: "ParsingXML. class. getClassLoader (). getResource --/D:/windpower/WebRoot/WEB-INF/classes /"
In addition, if you want to put the file in a package, you can obtain the directory where the file is located in the following way, that is, first locate the last level directory of the package.
ParsingXML. class. getResource (""). getPath ();
For example:
String path = ParsingXML. class. getResource (""). getPath ();
System. out. println ("ParsingXML. class. getResource ---" + p2 );
Print: "ParsingXML. class. getResource ---/D:/windpower/WebRoot/WEB-INF/classes/parsing/" (ParsingXML is the class in the parsing package under the src directory)
5. Read attribute files:
Method 1.
Static {
Ps = new Properties ();
Try {
InputStream in = ReadWrite. class. getResourceAsStream ("DeviceNO ");
Ps. load (in );
In. close ();
} Catch (Exception e ){
E. printStackTrace ();
}
Ps. getProperty ("key ")
Method 2.
Locale locale = Locale. getDefault ();
ResourceBundle localResource = ResourceBundle. getBundle ("windpower/DeviceNOProperties", locale );
String value = localResource. getString ("1 ");
System. out. println ("DeviceNO:" + value );
The DeviceNOProperties. properties file under the src directory of the project (the name suffix must be properties) is as follows: 1 = 3 the output result is: "DeviceNO: 3"
6. encoding conversion problems:
The getResource method of ClassLoader uses UTF-8 to encode the path information. When the path contains Chinese characters and spaces, it will convert these characters, the obtained path is often not the actual path we want. Here, we call the decode method of URLDecoder to decode the URL to obtain the original Chinese and space paths.
For example, the result is file:/C:/Documents ents % 20and % 20 Settings/% e5 % ba % 84% e6 % 99% e6 % af % 85.
/Local % 20 Settings/Temp/temp0.jar! /Db/d1_data. mdb
We expect the C:/Documents path p source and so on. Here we only need to decode the returned value before obtaining the path. use UTF-8 encoding. Java code:
String configPath = this. getClass (). getClassLoader (). getResource ("allowPath. xml"). getFile ();
ConfigPath = java.net. URLDecoder. decode (configPath, "UTF-8 ");
In addition, java.net. URLEncoder. encode (String s) and java.net. URLDecoder. decode (String s); In javascript, the URL encoding and decoding functions escape (String s) and unescape (String s );
VII. Summary:
When using relative paths, we should use relative paths relative to the current classpath.
The getResource (String name) and getResourceAsStream (String name) Methods of the ClassLoader class use the relative path relative to the classpath of the current project to find resources.
This is also true for getBundle (String path) of the ResourceBundle class that is commonly used to read attribute files.
By viewing the source code of the ClassLoader class and its related classes, it is found that it still uses an absolute path in URI form. Obtain the absolute path in the URI form of the current classpath, and then construct the absolute path in the URI form of the relative path.

Author: ERDP Technical Architecture"

Related Article

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.