"Java" path problem for Java

Source: Internet
Author: User

Sum up from many articles and books

In particular: http://blog.csdn.net/shendl/article/details/1427475 highly recommended

1. Get the path in the IDE

File F = new file ("Config.txt");

In the IDE if so F.getabsolutepath () the absolute path returned by this method is the Config.txt file in the root directory of this project

In Linux non-IDE, returns the value of the Config.txt file under the current path

File F = new file ("/config.txt");

The Config.txt file that is returned under Windows is the C drive, and the root directory is returned under Linux Config.txt

Principle:

The JVM obtains an absolute address through the corresponding path of the System.getproperty ("User.dir") and the string concatenation we wrote in file above, noting that the front does not add/

Attention

For a generic project this user.dir is the root path of the project

But this might not be the case with the files on the server.

So don't use this to find files.

  

Test:

The value of the user.dir varies depending on the directory where the generated. class file is located.

2. Read the path under Classpath

   1 , FileTest.class.getResource ("")

The URI directory of the current class Filetest.class file is obtained. Don't include yourself! (Contains the bin directory where the. class file resides and the package directory at all levels, excluding its own file name) such as: file:/d:/java/eclipse32/workspace/jbpmtest3/bin/com/test/2, FileTest.class.getResource ("/")Gets the absolute URI path of the current classpath. such as: file:/d:/java/eclipse32/workspace/jbpmtest3/bin/3, Thread.CurrentThread (). Getcontextclassloader (). GetResource ("")The resulting absolute URI path is also the current classpath. such as: file:/d:/java/eclipse32/workspace/jbpmtest3/bin/4, FileTest.class.getClassLoader (). GetResource ("")The resulting absolute URI path is also the current classpath. such as: file:/d:/java/eclipse32/workspace/jbpmtest3/bin/5, Classloader.getsystemresource ("")The resulting absolute URI path is also the current classpath. such as: file:/d:/java/eclipse32/workspace/jbpmtest3/bin/

  Recommended Use Thread.CurrentThread (). Getcontextclassloader (). GetResource ("") to get the URI representation of the absolute path of the current classpath.

Code:

    

This shows that the path obtained through file is the root directory of project

The path obtained by getresource in this form is the Classpath directory after the project is compiled, which is the bin directory

Where to get the file path is mainly used:

It is used primarily for reading from resources other than. class files, such as configuration files, to locate the files before they are read.

Absolute path is definitely not possible, because once you have changed the path or migrated to another computer, you cannot find the resource

So use a relative path.

Is the path of this resource relative to Classpath, the bin directory.

In the Javase program, these resource files are generally the same as the Classpath directory, which is the bin directory, so you can get the path directly using the Class.getResource method.

However, in Web applications, these resources are probably not stored in the Classpath directory, but in the Classpath directory parallel to the Web-inf directory

At this time with the original method can only locate the Classpath directory, and the absolute path is not possible, so it is necessary to re-write methods to find the path of the resource

The reason why you cannot locate a classpath parallel directory is because the GetResource method cannot be passed in. /Such a string to access the parent directory

So to solve this problem, only need to simulate a bit. /The actions you can make

Summarize:

Use the CLASSPATH path-based approach, and do not use the User.dir-based approach or the absolute path

The following code has not been read: Do not forget

Importjava.io.IOException;ImportJava.io.InputStream;Importjava.net.MalformedURLException;ImportJava.net.URL;Importjava.util.Properties;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory;/*** @author Shen Dongliang [email protected] *nov29,2006 10:34:34am * Used to load classes, classpath resource files, properties files, etc. *getextendresource (Stringrelativepath) method, you can use the: /symbol to load resources outside of classpath. */publicclass classloaderutil {privatestatic log log=logfactory.getlog (Classloaderutil.class); /***thread.currentthread (). Getcontextclassloader (). GetResource ("")*/       /*** Load Java classes. Use the fully qualified class name * @paramclassName *@return     */publicstatic Class loadclass (String className) {Try {          returngetClassLoader (). LoadClass (ClassName); } Catch(ClassNotFoundException e) {thrownew runtimeexception ("Class not found '" +classname+ "'", E); }     }     /*** Get class loader *@return       */publicstatic ClassLoader getClassLoader () {returnClassloaderutil.class. getClassLoader (); }     /*** Provides a resource path relative to Classpath, returns the input stream of the file * @paramrelativePath must pass the relative path of the resource. is the path relative to the classpath. If you need to find resources outside of classpath, you need to use: /To find *@returnfile Input stream * @throwsIOException * @throwsMalformedURLException*/publicstatic inputstream getstream (String relativepath)throwsmalformedurlexception, IOException {if(!relativepath.contains (".. /")){             returngetClassLoader (). getResourceAsStream (RelativePath); }Else{             returnClassloaderutil.getstreambyextendresource (RelativePath); }            }     /*** * @paramurl *@return* @throwsIOException*/publicstatic inputstream getstream (url url)throwsioexception{if(url!=NULL){                             returnUrl.openstream (); }Else{returnnull; }     }     /*** * @paramrelativePath must pass the relative path of the resource. is the path relative to the classpath. If you need to find resources outside of classpath, you need to use: /To find *@return* @throwsMalformedURLException * @throwsIOException*/publicstatic inputstream getstreambyextendresource (String relativepath)throwsmalformedurlexception, ioexception{returnClassloaderutil.getstream (Classloaderutil.getextendresource (RelativePath)); }           /*** Provides a resource path relative to Classpath, returns the Property object, which is a hash list * @paramresource *@return       */publicstatic Properties getProperties (String Resource) {Properties Properties=NewProperties (); Try{properties.load (GetStream (Resource)); } Catch(IOException e) {thrownew runtimeexception ("Couldn ' t load properties file '" +resource+ "", E); }        returnproperties; }     /*** Get the absolute path to the classpat of the ClassLoader where this class is located. *url form of *@return       */publicstatic String Getabsolutepathofclassloaderclasspath () {ClassLoaderUtil.log.info (C Lassloaderutil.getclassloader (). GetResource (""). toString ()); returnClassloaderutil.getclassloader (). GetResource (""). toString (); }     /*** * @paramrelativePath must pass the relative path of the resource. is the path relative to the classpath. If you need to find resources outside of classpath, you need to use: /To find the absolute URL of the * @return resource * @throwsMalformedURLException*/publicstatic URL getextendresource (String relativepath)throwsmalformedurlexception{ClassLoaderUtil.log.info ("Incoming relative path:" +relativepath); //ClassLoaderUtil.log.info (integer.valueof (Relativepath.indexof (". /"))) ;         if(!relativepath.contains (".. /")){             returnClassloaderutil.getresource (RelativePath); } String Classpathabsolutepath=Classloaderutil.getabsolutepathofclassloaderclasspath (); if(relativepath.substring (0, 1). Equals ("/") ) {RelativePath=relativepath.substring (1); } ClassLoaderUtil.log.info (Integer.valueof (Relativepath.lastindexof (".. /"))) ; String wildcardstring=relativepath.substring (0,relativepath.lastindexof (". /") +3); RelativePath=relativepath.substring (Relativepath.lastindexof (". /") +3); intContainsum=classloaderutil.containsum (wildcardstring, "... /"); Classpathabsolutepath= Classloaderutil.cutlaststring (Classpathabsolutepath, "/", containsum); String Resourceabsolutepath=classpathabsolutepath+RelativePath; ClassLoaderUtil.log.info ("Absolute path:" +Resourceabsolutepath); URL Resourceabsoluteurl=NewURL (Resourceabsolutepath); returnResourceabsoluteurl; }     /*** * @paramsource * @paramdest *@return       */privatestaticint containsum (String source,string dest) {intContainsum=0; intDestlength=dest.length ();  while(Source.contains (dest)) {containsum=containsum+1; SOURCE=source.substring (destlength); }                           returncontainsum; }     /*** * @paramsource * @paramdest * @paramnum *@return       */privatestatic string cutlaststring (String source,string dest,intnum) {         //String cutsource=null;          for(inti=0;i<num;i++) {Source=source.substring (0, Source.lastindexof (dest, Source.length ()-2) +1); }                                    returnsource; }     /*** * @paramresource *@return       */publicstatic URL getresource (String Resource) {ClassLoaderUtil.log.info ("Incoming path relative to Classpath:" +Resource); returnClassloaderutil.getclassloader (). getresource (Resource); }               /*** @paramargs * @throwsMalformedURLException*/publicstaticvoid Main (string[] args)throwsmalformedurlexception {//Classloaderutil.getextendresource ("..        /spring/dao.xml "); //Classloaderutil.getextendresource (".. /.. /.. /src/log4j.properties ");Classloaderutil.getextendresource ("Log4j.properties"); System.out.println (Classloaderutil.getclassloader (). GetResource ("Log4j.properties"). toString ()); } }

"Java" path problem for Java

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.