Java file path

Source: Internet
Author: User
Tags locale tomcat

getResourceAsStream () returns the InputStream

GetResource () return: URL

Class.getResource ("") returns the start of the package where the current class is located

Class.getResource ("/") returns the position of the Classpath

getClassLoader (). GetResource ("") returns the position of Classpath

getClassLoader (). GetResource ("/") wrong!!

========================================================================
Class.getresourceasstream and Classloader.getresourceasstream

These two methods are slightly different, have not been distinguished before, until today found to write such a code to run the error, before the problem clarified.

Basically, two can be used for resource reading from Classpath, Classpath contains the paths in Classpath and jars in Classpath.

The difference between the two methods is that the resource is defined differently, one is primarily used relative to an object resource, and the other is used to take the resource relative to the classpath, using an absolute path.

When using Class.getresourceasstream, there are two ways in which a resource path, one at/beginning, is to specify an absolute path, and if it does not start with/, the path is relative to the package where the class resides.

When using Classloader.getresourceasstream, the path directly uses the absolute path relative to the classpath.

For example, the following three statements, the actual result is the same

Com.explorers.Test.class.getResourceAsStream ("Abc.jpg")
Com.explorers.Test.class.getResourceAsStream ("/com/explorers/abc.jpg")
Classloader.getresourceasstream ("Com/explorers/abc.jpg")
================================================================================

Usually write the program, many times the hint file can not find, and thrown the exception, now sorted as follows


The acquisition of a relative path
Description: The relative path (that is, the relative who does not specify) can be obtained in the following ways (whether it is a general Java project or a Web project)
String relativelypath=system.getproperty ("User.dir");
In the relative path above, the files in the Java project are relative to the project's root directory
File paths in Web projects vary depending on the Web server (tomcat is relative to Tomcat installation directory \ Bin)


Acquisition of the second class loading directory (i.e. when the runtime gets its loading directory)
1 Common method One (whether it is a general Java project or a Web project, first navigate to the first level of directory to see the package path)

InputStream Is=testaction.class.getclassloader (). getResourceAsStream ("test.txt");
(The path to the Test.txt file is the project name \src\test.txt; class Testaction The first level of the package is located under the SRC directory)

Replace Testaction,test.txt with the corresponding class name and file name in the form

2 Common Method Two (this method is similar to the method in 1, but this method must start with '/')
InputStream Is=test1.class.getresourceasstream ("/test.txt");
(The path to the Test.txt file is the project name \src\test.txt, class Test1 the first level of the package is located under the SRC directory)

Acquisition of the root directory of three Web projects (after publication)
1 starting from the servlet

You can create a servlet to write the following statement in its Init method
ServletContext S1=this.getservletcontext ();
String Temp=s1.getrealpath ("/"); Key
Results in the form of: D:\ tool \tomcat-6.0\webapps\002_ext\ (002_ext for project name)

If the S1.getrealpath ("") is invoked, the output D:\ tool \tomcat-6.0\webapps\002_ext (one less "\")

2 Starting from HttpServletRequest

String cp11111=request.getsession (). Getservletcontext (). Getrealpath ("/");

Results in the form of: D:\ tool \tomcat-6.0\webapps\002_ext\

Four Classpath acquisition (in Eclipse for the path to the SRC or classes directory)

Method one Thread.CurrentThread (). Getcontextclassloader (). GetResource (""). GetPath ()


Eg:string T=thread.currentthread (). Getcontextclassloader (). GetResource (""). GetPath ();
SYSTEM.OUT.PRINTLN ("t---" +t);

Output: T---/e:/order/002_ext/webroot/web-inf/classes/


Method two JdomParse.class.getClassLoader (). GetResource (""). GetPath () (Jdomparse is a class in a package of SRC, hereinafter)

Eg:string P1=jdomparse.class.getclassloader (). GetResource (""). GetPath ();
System.out.println ("JdomParse.class.getClassLoader (). getresource--" +P1);

Output: JdomParse.class.getClassLoader (). getresource--/e:/order/002_ext/webroot/web-inf/classes/


In addition, if you want to put a file in a package, you can get to the file in the following ways (navigate to the last level of the package first)

eg String p2=jdomparse.class.getresource (""). GetPath ();
System.out.println ("JdomParse.class.getResource---" +p2);

Output: JdomParse.class.getResource---/e:/order/002_ext/webroot/web-inf/classes/jdom/(jdomparse is a class in the Jdom package under the SRC directory)


Read the Five property files:

Method One

InputStream in = Lnew bufferedinputstream (new FileInputStream (name));

Properties P = new properties ();

P.load (in);


Note the problem with the path, and after execution you can call P.getproperty ("name") to get the value of the corresponding property


Method Two

Locale Locale = Locale.getdefault ();
ResourceBundle Localresource = Resourcebundle.getbundle ("test/propertiestest", locale);
String value = localresource.getstring ("test");
System.out.println ("ResourceBundle:" + value);

Engineering src directory propertiestest.properties (name suffix must be properties) the contents of the file are as follows:

Test=hello Word


<span class= "KWRD" >public</span> <span class= "KWRD" >class</span> filetest {<span class= "K" WRD ">public</span> <span class=" KWRD ">static</span> <span class=" KWRD ">void</span > main (string[] args) {system.<span class= "KWRD" >out</span>.println (Thread.CurrentThread (). GetCont
        Extclassloader (). GetResource (<span class= "str" > "" </span>)); System.<span class= "KWRD" >out</span>.println (Filetest.<span class= "KWRD" &GT;CLASS&LT;/SPAN&GT;.
        getClassLoader (). GetResource (<span class= "str" > "" </span>)); System.<span class= "KWRD" >out</span>.println classloader.getsystemresource (<span class= "str" >
        "</span>)); System.<span class= "KWRD" >out</span>.println (Filetest.<span class= "KWRD" &GT;CLASS&LT;/SPAN&GT;.
        GetResource (<span class= "str" > "" </span>)); System.<span class= "KWRD" >out</span>.println (filetesT.<span class= "KWRD" >class</span>.getresource (<span class= "str" > "/" </span>)); <span class= "REM" >//class file path </span> system.<span class= "KWRD" >out</span>.println (<s
        Pan class= "KWRD" >new</span> File (<span class= "str" > "/" </span>). GetAbsolutePath ()); System.<span class= "KWRD" >out</span>.println system.getproperty (<span class= "str" > "User.dir"
    </span>)); }
}

Output results:

file:/e:/workspace/javastudy/bin/
file:/e:/workspace/javastudy/bin/
file:/e:/workspace/javastudy/bin/
file:/e:/workspace/javastudy/bin/test/
file:/e:/workspace/javastudy/bin/
E:\
E:\workspace\JavaStudy

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.