Java gets directory information where it runs

Source: Internet
Author: User

For a Java program, whether it's an unpackaged or packaged jar or war file, sometimes you need to get the directory information it's running in, how do you do that?   In a Java-processed file system, the directory is represented in two:  (1) absolute directories, with "/" as the starting character, representing the directory from which the root directory was found, such as the/c:/java  (2) relative path, which is represented by a directory name without a "/". Represents the directory in which the current Java program is running as the starting directory to look for. such as java/classes. In the relative path, there are certain characters that can represent special directories, for example, "." Represents the current directory, "..." Represents the top-level directory of the current directory. In many of the examples given online, the use of "." Constructs an instance of the file object as a directory name, and then obtains the directory that the current program runs by using the file object's method.       Although this method is simple, sometimes it is not possible to correctly draw the current program's running directory. The reason is that running a Java program does not have to go into the directory of the program's class file or jar file, as long as you specify the correct classpath information at run time, you can run a Java program in any directory, this method can only get the directory information where the command was issued.        from the above analysis, we can see that for many Java programs, especially web programs, the "." of the current path is used. Representations, are not sufficient to meet the requirements. So how do you get the running directory information correctly?        in a Web program, you can get some path information using SERVLET&NBSP;API, For example, the Getrealpath method defined in the HttpServletRequest interface, but similar to these methods are dependent on the servlet environment, not easy to program unit testing.       This article provides a path detection method that uses only the Java standard API, which is the use of ClassLoader abstract classes.       Using the getClassLoader method of Java.lang.Class, the ClassLoader instance of the given class can be obtained, its GetResource method can get the position of the resources in the current class loader, we can use the name of the class file as the resource to find, and after processing, we can get the The running location information of the former Java program, the pseudo code is as follows: &NBsp;        get the class name where the class parameter is located       get the package name that contains it        Convert package name to path       use GetResource to get the current class file location url       use URL to resolve the current Java program's path   specific code is as follows: Java code: Java code  /**------------------------------------------ -----------------------------     *getapppath needs a class attribute parameter for the Java class used by the current program, which can return the packaged The      *java executable file (Jar,war) is located in the system directory name or the directory      * the non-packaged Java program @param  cls for class type      * @return   return value for the directory where the Java program in which the class is running       -------------------------------------------------------------------------*/      public static string getapppath (CLASS&NBSP;CLS) {          //Check if the parameter passed in by the user is empty          if (cls==null)          &Nbsp;  throw new java.lang.illegalargumentexception ("parameter cannot be empty!") ");          classloader loader=cls.getclassloader ();          //get the full name of the class, including the package name           string clsname=cls.getname () + ". Class";          // Get the package          package pack=cls.getpackage () that contains the incoming parameter;          string path= "";          //if it is not an anonymous package, convert the package name to Path          if (pack!=null) {              string packname=pack.getname ();             //here to determine whether it is a Java base Class library to prevent users from passing into the JDK's built-in class library           &nbsP; if (Packname.startswith ("java.") | | Packname.startswith ("javax."))                 throw new  java.lang.illegalargumentexception ("Do not transfer the system class!              //. In the name of the class, remove the part of the package name to get the file name of the class              clsname=clsname.substring ( Packname.length () +1);              // Determines whether the package name is a simple package name, and if so, converts the package name directly to a path,              if ( Packname.indexof (".") <0)  path=packname+ "/";              else{//Otherwise, the package name will be converted to a path according to the package name                   int start=0,end=0;            &nbSp;     end=packname.indexof (".");                  while ( End!=-1) {                      path=path+packname.substring (start,end) + "/";                      start=end+1;                       end=packname.indexof (".", start);                  }                  path=path+packname.substring (start) + "/";              }         }         //calls ClassLoader's GetResource method, Pass in the class file name that contains the path information          java.net.url url = Loader.getresource (path+clsname);          //get path information from the URL object           string realpath=url.getpath ();          //Remove the protocol name "file:" In the path information          int  pos=realpath.indexof ("File:");          if (pos>-1)   Realpath=realpath.substring (pos+5)          //Remove the part of the path information that finally contains the class file information, Get the path where the class is located          pos=realpath.indexof (path+clsname);          realpath=realpath.substring (0,pos-1);          //if a class file is packaged into a file such as a jar, remove the package file name          if (Realpath.endswith ("!")) from the corresponding jar.              realpath=realpath.substring (0, Realpath.lastindexof ("/"));        /*--------------------------------------- The GetResource method of the---------------------       classloader uses the utf-8 to encode the path information when the path          in the presence of Chinese and white space, he will convert these characters, so that often not we want to get      The true path of     , in this case, calls the Urldecoder decode method to decode in order to get the original           Chinese and Space path       ------------------------------------------------------------- */       try{         realpath =java.net.urldecoder.decode (Realpath, "Utf-8");         }catch (Exception  e) {throw new  RuntimeException (e);}         return realpath;     }// Getapppath Define End     //-----------------------------------------------------------------    This method can be used for either a jar or war file or a non-jar file. But note the following 2 points:  do not pass the system class, as Getapppath parameters, such as Java.lang.String.class, of course, do not pass those that are already in the JDK, such as some of the classes of XML related and so on. To pass should be the main running class in the program, do not pass the class files in the supporting class library in the program, that is, the class files in the third-party class library, otherwise the location of those class libraries will be obtained.   can then increase the boot entry by modifying the registry: Reprint: Registry key to be modified  [hkey_local_machine\software\microsoft\windows\currentversion\run]    Boot Autorun program [hkey_local_machine\software\microsoft\windows\currentversion\runonce]  start automatically run program     Run only once  [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices]  boot Autorun service JDK   from 1.4 to provide operation  Windows   API  is  preferences, because this  API  is also cross-platform, the function is relatively weak, in the   win32  can only be used to manipulate  HKCU\Software\JavaSoft  and  HKLM\Software\JavaSoft  and sub-node data. Free access to the registry other key values light with &NBSP;JAVA&NBSP, is not to be done, the inevitable plan is  jni, here I use is windows registry api native interface http:// www.trustice.com/java/jnireg/index.shtml  under  registry-3.1.3.zip (contains source code). You can use it to access, modify, export registry entries to files, and so on. Unlock  registry-3.1.3.zip, you can see two files in the  bin  directory  ICE_JNIRegistry.dll  and   Registry.jar, a dynamic library is a native code implementation. Com.ice.jni.registry.Registry.main ()   is the sample code for  registry , dynamic library  ICE_JNIRegistry.dll  is also loaded in the static block of this class, remember to put  ICE_JNIRegistry.dll  in the position where it can be loaded, for example, you extract  registry-3.1.3.zip  to  c:\ registry-3.1.3, at the command line you can enter into this directory and execute. Code: Java Code  package org.zh.ss.util;    import com.ice.jni.registry.*;   import java.text.simpledateformat;    /** *//**  * java   Operations Registry    *  @author   Zhiyuan Li   */  public class  regedittool {        static simpledateformat  ShortdateformaT = new simpledateformat ("Yyyy-mm-dd");         /**  *//** */      /** *//** Creates a new  instance of test */        //  storing information in the registry Hkey_local_ A variable in one of the nodes under machine is modified, and none is created       public static boolean setvalue (string folder, string subkeynode,               string subkeyname, string subkeyvalue)  {           try {               RegistryKey software = Registry.HKEY_LOCAL_MACHINE                        .opensubkey (folder);               registrykey subkey =  software.createsubkey (subkeynode,  "");               subKey                       .setvalue (New regstringvalue (subKey,  subkeyname,                               subkeyvalue));               subkey.closekey ();               return true;           } catch  (nosuchkeyexception e)  {          &Nbsp;    e.printstacktrace ();           }  catch  (nosuchvalueexception e)  {               e.printstacktrace ();           } catch  (registryexception e)  {               e.printstacktrace ();           }          return false;       }        //  Delete a variable under a node in the registry        public static boolean deletevalue (string folder, string subkeynode,               string subkeyname)  {                     try {               registrykey software  = Registry.HKEY_LOCAL_MACHINE                       .opensubkey (folder);               RegistryKey subKey =  Software.createsubkey (subkeynode,  "");               subkey.deletevalue (subkeyname);               subkey.closekey ();               return true;          } catch   (nosuchkeyexception e)  {              system.out.println (" Nosuchkey_delete ");          } catch  ( Nosuchvalueexception e)  {               system.out.println ("Nosuchvalue_delete");           } catch  (registryexception e)  {               e.printstacktrace ();           }          return false;       }        //  Delete a node under a node in the registry        public static boolean deletesubkey (String folder, string subkeynode)  {          try {               RegistryKey software = Registry.HKEY_LOCAL_MACHINE                       . OpenSubKey (folder);               Software.deletesubkey (Subkeynode);               software.closekey ();               return true;          } catch  ( Nosuchkeyexception e)  {               e.printstacktrace ();          } catch  (registryexception e) &NBSP;{&NBSP;&NBSP;&NBSp;           e.printstacktrace ();           }          return  false;      }        //  Open the registry key and read out the value of the corresponding variable name       public static string getvalue (String  folder, string subkeynode,               string subkeyname)  {          string  value =  "";          try {               RegistryKey software =  registry.hkey_local_machine                        .opensubkey (folder);               registrykey subkey = software.opensubkey (SubKeyNode);               value = subkey.getstringvalue ( SubkeyName);               Subkey.closekey ();          } catch  ( Nosuchkeyexception e)  {               value =  "Nosuchkey";               // e.printstacktrace ();           }  catch  (nosuchvalueexception e)  {               value =  "NosuchvaluE ";              //  E.printstacktrace ();          } catch  ( Registryexception e)  {               e.printstacktrace ();          }           return value;      }         //  Test       public static void  main (String[] args)  {          setvalue (" Software ", " Microsoft\\windows\\currentversion\\run ", " test ",                    "C:\\1.exe");       }  }


Java gets directory information where it runs

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.