title: Execute Java jar from it's directory using java program
body: <p>I am trying to execute another java jar using <code>ClassLoader</code>, once this jar is executed. It looks for certain file in it's directory.</p>
  
  <p>How do I setup the working directory when I start this jar?</p>
  
  <p>I used <code>System.setProperty("user.dir", "C:\\abc");</code> before starting the jar but, it's not working.</p>
  
  <p>I am trying to start the jar in another thread
  and before starting the jar I am trying to set the working directory.</p>
  
  <pre><code>System.setProperty("user.dir", "C:\\abc");
  File jarfile = new File("myjar.jar");
  Manifest manifest = jar.getManifest();
  Attributes attrs = manifest.getMainAttributes();
  String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS);
  URL url = new URL("file", null, jarfile.getCanonicalPath());
  ClassLoader cl = new URLClassLoader(new URL[] { url });
  Class&lt;?&gt; mainClass = cl.loadClass(mainClassName);
  Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class });
  mainMethod.setAccessible(true);
  int mods = mainMethod.getModifiers();
  
     if (mainMethod.getReturnType() != void.class
          || !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
      throw new NoSuchMethodException("main");
  }
  String[] args2 = new String[1];
  args2[0] = "service=slave";
  mainMethod.invoke(mainClass, new Object[] { args2 });
  </code></pre>