Java gets the path of the current class

Source: Internet
Author: User

Recently in the project, I wrote some configuration parameters read, put the configuration file in a specific location, and then let the program based on the path of the current class to find the path of the configuration file, but found that the development of eclipse in the bad environment can be successfully read into the configuration file under the specified path configuration parameters,

However, when the project is placed under Tomcat or packaged into an executable jar package, the compiled class file is not readable by the configuration file found in the development environment.

If you write directly in the. java File//public static String Config = "Config.properties"; The path to the project's SRC sibling (directly placing the configuration file in the project's root directory)

After looking up the data and verifying, the method of reading the configuration file of the class file relative to the path is summarized as follows:

Method One: Use the system to get the path

Method Two: Get the path using the Protectiondomain or ClassLoader of the current class

Method Three: Use thread to get the path

Method One:

Example:

public static final String urlconfig = System.getproperty ("User.dir"). Replace ("Bin", "WebApps") + "/ Urlconfig.properties ";//This is the directory where the configuration files are placed into Tomcat's WebApps

Where the System.getproperty ("User.dir") is to get the user's current working directory

The Java System.getproperty () method can get the value

Get the code example:

 Public   classSystemproperty { Public   Static   voidMain (String args[]) {System.out.println ("Java_vendor:" + system.getproperty ("Java.vendor" )); System.out.println ("Java_vendor_url:" + system.getproperty ("Java.vendor.url" )); System.out.println ("Java_home:" + system.getproperty ("Java.home" )); System.out.println ("Java_class_version:" + system.getproperty ("Java.class.version" )); System.out.println ("Java_class_path:" + system.getproperty ("Java.class.path" )); System.out.println ("Os_name:" + system.getproperty ("Os.name" )); System.out.println ("Os_arch:" + system.getproperty ("Os.arch" )); System.out.println ("Os_version:" + system.getproperty ("Os.version" )); System.out.println ("User_name:" + system.getproperty ("User.Name" )); System.out.println ("User_home:" + system.getproperty ("User.home" )); System.out.println ("User_dir:" + system.getproperty ("User.dir" )); System.out.println ("Java_vm_specification_version:" + system.getproperty ("Java.vm.specification.version" )); System.out.println ("Java_vm_specification_vendor:" + system.getproperty ("Java.vm.specification.vendor" )); System.out.println ("Java_vm_specification_name:" + system.getproperty ("Java.vm.specification.name" )); System.out.println ("Java_vm_version:" + system.getproperty ("Java.vm.version" )); System.out.println ("Java_vm_vendor:" + system.getproperty ("Java.vm.vendor" )); System.out. println ("Java_vm_name:" + system.getproperty ("Java.vm.name" )); System.out.println ("Java_ext_dirs:" + system.getproperty ("Java.ext.dirs" )); System.out.println ("File_separator:" + system.getproperty ("File.separator" )); System.out.println ("Path_separator:" + system.getproperty ("Path.separator" )); System.out.println ("Line_separator:" + system.getproperty ("Line.separator" )); }     

The above example refers to the blog address: 51895823

Method Two:

Example 1:

 Public StaticString Getmydir () {//gets the absolute path of the current class fileString Jarwholepath = Configerpraram.class. Getprotectiondomain (). Getcodesource (). GetLocation (). GetFile ();Try { //for the sake of insurance, decode transcoding the pathJarwholepath = Java.net.URLDecoder.decode (Jarwholepath, "UTF-8"); } Catch(unsupportedencodingexception e) {System.out.println (e.tostring ());}//get the parent directory of the JAR packageString Jarpath =NewFile (Jarwholepath). Getparentfile (). GetAbsolutePath ();returnJarpath;}

Example 2:

 /**   * Get Project path * *   @return  */ public " Span style= "COLOR: #0000ff" >static   String Getrealpath () {
// The absolute path of the jar package is obtained through the class loader String realpath
= MyPath. class . getClassLoader (). GetResource ("). GE Tfile (); Java.io.File File = new Java.io.File ( Realpath); Realpath = file . Getparentfile (). GetAbsolutePath (); Gets the parent directory of the JAR package
Try  {
Path decode transcoding
= Java.net.URLDecoder.decode (Realpath, "Utf-8"); Catch  (Exception e) { e.printstacktrace (); }
}

Method Three: (the method has not yet done validation, citing blogs: 22774537)

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

Application can be obtained directly at the classes level through the new FileInputStream ("Xx.properties"). The point is that sometimes we need to modify the configuration file via the Web, and we can't write the path dead. After the test feel the following experience:

Read and write in 1.servlet. If using struts or a servlet can be configured directly in the initialization parameters, the call is based on the servlet's Getrealpath ("/") to get the real path, and then the string file = This.servlet.getInitParameter ("abc"); Gets the relative path of the relative Web-inf.
Cases:
InputStream input =thread.currentthread (). Getcontextclassloader (). getResourceAsStream ("abc.properties");
Properties prop = new properties ();
Prop.load (input);
Input.close ();

Prop.setproperty ("abc", "Test");
Prop.store (new FileOutputStream (path), "–test–");
Out.close ();

2. Directly in the JSP operation, through the JSP built-in object to get an operational absolute address.
Cases:
JSP page
String path = Pagecontext.getservletcontext (). Getrealpath ("/");
String Realpath = path+ "/web-inf/classes/abc.properties";

Java programs
InputStream in = GetClass (). getClassLoader (). getResourceAsStream ("abc.properties"); Abc.properties placed in the webroot/web-inf/classes/directory
Prop.load (in);
In.close ();

OutputStream out = new FileOutputStream (path); Path is passed through the page
Prop.setproperty ("abc", "ABCCCCCC");
Prop.store (out, "–test–");
Out.close ();

3. Manipulate resource files only through Java programs
InputStream in = new FileInputStream ("Abc.properties"); Relative path, path under Project

OutputStream out = new FileOutputStream ("Abc.properties");

The following references are explained in the blog: https://www.cnblogs.com/gaoxing/p/4703412.html

For a simple analogy, you run a Web program that publishes into Tomcat.
The first is to execute the Tomcat Org.apache.catalina.startup.Bootstrap class, when the ClassLoader is Classloader.getsystemclassloader ().
The Web program behind us, inside the jar, resources are loaded by tomcat inside, so you in the code to dynamically load the jar, resource files, the first should be the use of Thread.CurrentThread (). Getcontextclassloader (). If you use Test.class.getClassLoader (), it may cause inconsistencies with the classloader that the current thread is running (because Java is inherently multithreaded).
Test.class.getClassLoader () is generally used in getresource, because the location of the resource file is relatively fixed when you want to get a resource file.

Java's class loading mechanism (JVM specification) is a delegate model, which simply says that if a classloader wants to load a class, first it will delegate to its parent to load it, and if all of its parent does not load successfully then it will come in person, a bit like the way his son is trying to make me feel.

If you use Test.class.getClassLoader (), it may cause inconsistencies with the classloader that the current thread is running: Returns the class loader for the class Class.getClassLoader() . Some implementations may use NULL to represent the bootstrap class loader. This method would return null in such implementations if this class is loaded by the Bootstrap class loader.

Java gets the path of the current class

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.