Java: URL.getPath() of current “main” class returns “null”, why?












0















I'm trying to print the current path of class that executes main(), as below. I found the statements below from googling, but doesn't work in my computer(windows+intellij)



public class core3 {
public static void main(String args) {
try {
URL url = new core3().getClass().getClassLoader().getResource("");
System.out.println(url);
System.out.println(System.getProperty(url.getPath()));//print null
} catch (Exception e) {
e.printStackTrace();
}
}
}


Actually it prints



file:/D:/Documents/myproject/test01/target/classes/
null


Why the second print returns null? How to fix it?



Thanks










share|improve this question























  • Why do expect for system properties to contain that path?

    – user10639668
    Nov 24 '18 at 10:02
















0















I'm trying to print the current path of class that executes main(), as below. I found the statements below from googling, but doesn't work in my computer(windows+intellij)



public class core3 {
public static void main(String args) {
try {
URL url = new core3().getClass().getClassLoader().getResource("");
System.out.println(url);
System.out.println(System.getProperty(url.getPath()));//print null
} catch (Exception e) {
e.printStackTrace();
}
}
}


Actually it prints



file:/D:/Documents/myproject/test01/target/classes/
null


Why the second print returns null? How to fix it?



Thanks










share|improve this question























  • Why do expect for system properties to contain that path?

    – user10639668
    Nov 24 '18 at 10:02














0












0








0








I'm trying to print the current path of class that executes main(), as below. I found the statements below from googling, but doesn't work in my computer(windows+intellij)



public class core3 {
public static void main(String args) {
try {
URL url = new core3().getClass().getClassLoader().getResource("");
System.out.println(url);
System.out.println(System.getProperty(url.getPath()));//print null
} catch (Exception e) {
e.printStackTrace();
}
}
}


Actually it prints



file:/D:/Documents/myproject/test01/target/classes/
null


Why the second print returns null? How to fix it?



Thanks










share|improve this question














I'm trying to print the current path of class that executes main(), as below. I found the statements below from googling, but doesn't work in my computer(windows+intellij)



public class core3 {
public static void main(String args) {
try {
URL url = new core3().getClass().getClassLoader().getResource("");
System.out.println(url);
System.out.println(System.getProperty(url.getPath()));//print null
} catch (Exception e) {
e.printStackTrace();
}
}
}


Actually it prints



file:/D:/Documents/myproject/test01/target/classes/
null


Why the second print returns null? How to fix it?



Thanks







java class url path main






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 24 '18 at 9:49









TroskyvsTroskyvs

2,33821029




2,33821029













  • Why do expect for system properties to contain that path?

    – user10639668
    Nov 24 '18 at 10:02



















  • Why do expect for system properties to contain that path?

    – user10639668
    Nov 24 '18 at 10:02

















Why do expect for system properties to contain that path?

– user10639668
Nov 24 '18 at 10:02





Why do expect for system properties to contain that path?

– user10639668
Nov 24 '18 at 10:02












2 Answers
2






active

oldest

votes


















0














System.getProperty() is for getting system properties. For example, the "java.home" system property typically points to the location of your Java installation. System properties are described here.



Your code is looking up a system property with key equal to your URL. You do not have such a system property defined, so System.getProperty() returns null.



If you just want to print the path, you should simply omit the System.getProperty() call:



System.out.println(url.getPath());





share|improve this answer

































    0















    Why the second print returns null?




    Because you are attempting to lookup a system property that doesn't exist.



    This is not the way to find the path for the Main class.



    What you need to do is:





    1. Obtain the fully qualified (or canonical) name for the class; e.g.



        String name = Main.class.getCanonicalName();



    2. Map that to the resource path for the ".class" file. You need to:




      • replace all "." characters in full classname with "/", and then

      • append ".class".



    3. Use getResource(resourcePath) to lookup the URL.



    If the resulting URL is a "file:" URL, you can then use URL::toFile() to get the pathname in the file system.



    But if the URL is a "jar:" URL (as it will be if you loaded the class from a JAR file) the the class will not have a file system pathname.





    Note that getClassLoader().getResource("") gives you the path for the classloader's root directory. That's not the path for the original class.





    And if you want the name of the JVM class that calls your static void main(String) method, then you should be able to get this using the Java 9+ StackWalker class (javadoc). You will need to use the option to show the hidden frames, I think.






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53456984%2fjava-url-getpath-of-current-main-class-returns-null-why%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      System.getProperty() is for getting system properties. For example, the "java.home" system property typically points to the location of your Java installation. System properties are described here.



      Your code is looking up a system property with key equal to your URL. You do not have such a system property defined, so System.getProperty() returns null.



      If you just want to print the path, you should simply omit the System.getProperty() call:



      System.out.println(url.getPath());





      share|improve this answer






























        0














        System.getProperty() is for getting system properties. For example, the "java.home" system property typically points to the location of your Java installation. System properties are described here.



        Your code is looking up a system property with key equal to your URL. You do not have such a system property defined, so System.getProperty() returns null.



        If you just want to print the path, you should simply omit the System.getProperty() call:



        System.out.println(url.getPath());





        share|improve this answer




























          0












          0








          0







          System.getProperty() is for getting system properties. For example, the "java.home" system property typically points to the location of your Java installation. System properties are described here.



          Your code is looking up a system property with key equal to your URL. You do not have such a system property defined, so System.getProperty() returns null.



          If you just want to print the path, you should simply omit the System.getProperty() call:



          System.out.println(url.getPath());





          share|improve this answer















          System.getProperty() is for getting system properties. For example, the "java.home" system property typically points to the location of your Java installation. System properties are described here.



          Your code is looking up a system property with key equal to your URL. You do not have such a system property defined, so System.getProperty() returns null.



          If you just want to print the path, you should simply omit the System.getProperty() call:



          System.out.println(url.getPath());






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 24 '18 at 10:02

























          answered Nov 24 '18 at 9:54









          AutoAnswererAutoAnswerer

          284




          284

























              0















              Why the second print returns null?




              Because you are attempting to lookup a system property that doesn't exist.



              This is not the way to find the path for the Main class.



              What you need to do is:





              1. Obtain the fully qualified (or canonical) name for the class; e.g.



                  String name = Main.class.getCanonicalName();



              2. Map that to the resource path for the ".class" file. You need to:




                • replace all "." characters in full classname with "/", and then

                • append ".class".



              3. Use getResource(resourcePath) to lookup the URL.



              If the resulting URL is a "file:" URL, you can then use URL::toFile() to get the pathname in the file system.



              But if the URL is a "jar:" URL (as it will be if you loaded the class from a JAR file) the the class will not have a file system pathname.





              Note that getClassLoader().getResource("") gives you the path for the classloader's root directory. That's not the path for the original class.





              And if you want the name of the JVM class that calls your static void main(String) method, then you should be able to get this using the Java 9+ StackWalker class (javadoc). You will need to use the option to show the hidden frames, I think.






              share|improve this answer






























                0















                Why the second print returns null?




                Because you are attempting to lookup a system property that doesn't exist.



                This is not the way to find the path for the Main class.



                What you need to do is:





                1. Obtain the fully qualified (or canonical) name for the class; e.g.



                    String name = Main.class.getCanonicalName();



                2. Map that to the resource path for the ".class" file. You need to:




                  • replace all "." characters in full classname with "/", and then

                  • append ".class".



                3. Use getResource(resourcePath) to lookup the URL.



                If the resulting URL is a "file:" URL, you can then use URL::toFile() to get the pathname in the file system.



                But if the URL is a "jar:" URL (as it will be if you loaded the class from a JAR file) the the class will not have a file system pathname.





                Note that getClassLoader().getResource("") gives you the path for the classloader's root directory. That's not the path for the original class.





                And if you want the name of the JVM class that calls your static void main(String) method, then you should be able to get this using the Java 9+ StackWalker class (javadoc). You will need to use the option to show the hidden frames, I think.






                share|improve this answer




























                  0












                  0








                  0








                  Why the second print returns null?




                  Because you are attempting to lookup a system property that doesn't exist.



                  This is not the way to find the path for the Main class.



                  What you need to do is:





                  1. Obtain the fully qualified (or canonical) name for the class; e.g.



                      String name = Main.class.getCanonicalName();



                  2. Map that to the resource path for the ".class" file. You need to:




                    • replace all "." characters in full classname with "/", and then

                    • append ".class".



                  3. Use getResource(resourcePath) to lookup the URL.



                  If the resulting URL is a "file:" URL, you can then use URL::toFile() to get the pathname in the file system.



                  But if the URL is a "jar:" URL (as it will be if you loaded the class from a JAR file) the the class will not have a file system pathname.





                  Note that getClassLoader().getResource("") gives you the path for the classloader's root directory. That's not the path for the original class.





                  And if you want the name of the JVM class that calls your static void main(String) method, then you should be able to get this using the Java 9+ StackWalker class (javadoc). You will need to use the option to show the hidden frames, I think.






                  share|improve this answer
















                  Why the second print returns null?




                  Because you are attempting to lookup a system property that doesn't exist.



                  This is not the way to find the path for the Main class.



                  What you need to do is:





                  1. Obtain the fully qualified (or canonical) name for the class; e.g.



                      String name = Main.class.getCanonicalName();



                  2. Map that to the resource path for the ".class" file. You need to:




                    • replace all "." characters in full classname with "/", and then

                    • append ".class".



                  3. Use getResource(resourcePath) to lookup the URL.



                  If the resulting URL is a "file:" URL, you can then use URL::toFile() to get the pathname in the file system.



                  But if the URL is a "jar:" URL (as it will be if you loaded the class from a JAR file) the the class will not have a file system pathname.





                  Note that getClassLoader().getResource("") gives you the path for the classloader's root directory. That's not the path for the original class.





                  And if you want the name of the JVM class that calls your static void main(String) method, then you should be able to get this using the Java 9+ StackWalker class (javadoc). You will need to use the option to show the hidden frames, I think.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 24 '18 at 10:53

























                  answered Nov 24 '18 at 10:11









                  Stephen CStephen C

                  515k69563920




                  515k69563920






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53456984%2fjava-url-getpath-of-current-main-class-returns-null-why%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Contact image not getting when fetch all contact list from iPhone by CNContact

                      Insert data from modal to MySQL (multiple modal on website)

                      count number of partitions of a set with n elements into k subsets