title: How to get the path of running java program
body: <p>Is there a way to get the path of main class of the running java program.</p>
  
  <p>structure is</p>
  
  <pre><code>D:/
  |---Project
         |------bin
         |------src
  </code></pre>
  
  <p>I want to get the path as <code>D:\Project\bin\</code>.</p>
  
  <p>I tried <code>System.getProperty("java.class.path");</code> but the problem is, if I run like </p>
  
  <pre><code>java -classpath D:\Project\bin;D:\Project\src\  Main
  
  Output 
  Getting : D:\Project\bin;D:\Project\src\
  Want    : D:\Project\bin
  </code></pre>
  
  <p>Is there any way to do this?</p>
  
  <hr>
  
  <hr>
  
  <p><strong>=====  EDIT  =====</strong></p>
  
  <p><em>Got the <strong>solution</strong> here</em></p>
  
  <p><a href="https://stackoverflow.com/a/227569/2260473"><strong>Solution 1</strong></a> (By <a href="https://stackoverflow.com/users/22656/jon-skeet">Jon Skeet</a>)</p>
  
  <pre><code>package foo;
  
  public class Test
  {
      public static void main(String[] args)
      {
          ClassLoader loader = Test.class.getClassLoader();
          System.out.println(loader.getResource("foo/Test.class"));
      }
  }
  </code></pre>
  
  <p>This printed out:</p>
  
  <pre><code>file:/C:/Users/Jon/Test/foo/Test.class
  </code></pre>
  
  <p><br></p>
  
  <p><a href="https://stackoverflow.com/a/778246/2260473"><strong>Solution 2</strong></a> (By <a href="https://stackoverflow.com/users/3474/erickson">Erickson</a>)</p>
  
  <pre><code>URL main = Main.class.getResource("Main.class");
  if (!"file".equalsIgnoreCase(main.getProtocol()))
    throw new IllegalStateException("Main class is not stored in a file.");
  File path = new File(main.getPath());
  </code></pre>
  
  <p>Note that most class files are assembled into JAR files so this won't work in every case (hence the <code>IllegalStateException</code>). However, you can locate the JAR that contains the class with this technique, and you can get the content of the class file by substituting a call to <code>getResourceAsStream()</code> in place of <code>getResource()</code>, and that will work whether the class is on the file system or in a JAR.</p>