Java file path

Source: Internet
Author: User
Tags root access

Some of the most common methods

Class.getResource ("") returns the position of the current class where the package begins

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

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

Note:

What is Classpath? What is the role of it?
It is an environment variable of the Javac compiler.
Its role is related to import, the package keyword.
When you write down Improt java.util.*, when the compiler faces the import keyword, you know you want to introduce java.util the class in the package, but how does the compiler know where you put the package? So you first have to tell the compiler where the package is located, and how do you tell it? is to set classpath:) If java.util this package in the C:\jdk\ directory, you have to set c:\jdk\ this path to Classpath! When the compiler faces the import java.util.* this statement, it first looks for the directory specified by Classpath and checks to see if the subdirectory java\util exists, and then finds the compiled file (. class file) that matches the name. If you do not find it will be an error!

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

These two methods are still slightly different, have not been differentiated until today to find out to write such code when the run error, only to clarify the problem.

Basically, two can be used to read resources from Classpath, Classpath contains the path in Classpath and the jar in Classpath.

The difference between the two methods is that the definition of the resource is different, one is used to take the resource relative to one object, and the other is to take the resource relative to the classpath, using the absolute path.

When using Class.getresourceasstream, the resource path has two ways, one with/begins, then the path is the absolute path, and if not/begins, the path is relative to the package that the class resides in.

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

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 when, many times the hint file can not find, and throw an exception, now tidy up as follows


The acquisition of a relative path  
    Description: Relative paths (that is, those that do not specify when it is relative) can be obtained in the following ways (whether it is a generic 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 the Tomcat installation directory \ Bin)


The acquisition of a Class II loaded directory (that is, when a class of runtime obtains its loading directory)
1) Common method One (whether it is a generic Java project or a Web project, first navigate to the first level directory where you can 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; The first-level directory of the class Testaction package is located in the SRC directory)

Replace the testaction,test.txt with the corresponding class name and file name.

2) General method Two (this method is similar to the method in 1, the difference is that 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, and the first-level directory of the class Test1 package is located in the SRC directory)

Three Web project root access (after publishing)
1 departing from the servlet

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

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

2 Departure from HttpServletRequest

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

Result shape: D:\ tool \tomcat-6.0\webapps\002_ext\

Acquisition of four classpath (the path to get SRC or classes directories in Eclipse)

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 the SRC package, same as below)

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 the file in a package, you can get to the file in the following way (navigate to the last level of the package)

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 the class in the SRC Directory jdom package)


Read the five properties file:

Method One

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

Properties P = new properties ();

P.load (in);


Notice the problem of the path, after doing the execution 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);

Project SRC directory under propertiestest.properties (name suffix must be properties) file content is as follows:

Test=hello Word

PublicClass Filetest {PublicStaticvoid Main (string[] args) {system. Out.println (Thread.CurrentThread (). Getcontextclassloader (). GetResource (out.println (Filetest. Class.getclassloader (). GetResource (out.println (Classloader.getsystemresource (out.println (Filetest. Class.getResource (out.println (Filetest. Class.getResource (//class file is located in the path System. out.println (new File ( "/"). GetAbsolutePath ()); System. out.println (System.getproperty ( "User.dir"));}      

Output Result:

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

Java file path

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.