Five ways to get the class load path and project root path in Java

  • 2020-04-01 01:47:26
  • OfStack


package my;

 import java.io.File;
 import java.io.IOException;
 import java.net.URL;

 public class MyUrlDemo {

     
     public static void main(String[] args) {
         MyUrlDemo muDemo = new MyUrlDemo();
         try {
             muDemo.showURL();
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }

     public void showURL() throws IOException {

         //The first: gets the root path of the class load & NBSP;   D:  git  daotie  daotie  target  classes
         File f = new File(this.getClass().getResource("/").getPath());
         System.out.println(f);

         //Gets the project path of the current class; If you don't add the "/" & cake; Gets the load directory & NBSP; of the current class; D:  git  daotie  daotie  target  classes  my
         File f2 = new File(this.getClass().getResource("").getPath());
         System.out.println(f2);

         //Second: getting the project path & NBSP;     D:  git  daotie  daotie
         File directory = new File("");//Parameter is null
         String courseFile = directory.getCanonicalPath();
         System.out.println(courseFile);

 
         //Third: & NBSP; File: / D: / git/daotie/daotie/target/classes /
         URL xmlpath = this.getClass().getClassLoader().getResource("");
         System.out.println(xmlpath);

 
         //D:gitdaotiedaotie
         System.out.println(System.getProperty("user.dir"));
         

         //Fifth: & NBSP; Gets the path to all the classpaths, including the jars
         System.out.println(System.getProperty("java.class.path"));

     }
 }

Related articles: