0

I am trying to execute another java jar using ClassLoader, once this jar is executed. It looks for certain file in it's directory.

How do I setup the working directory when I start this jar?

I used System.setProperty("user.dir", "C:\\abc"); before starting the jar but, it's not working.

I am trying to start the jar in another thread and before starting the jar I am trying to set the working directory.

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<?> 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 });
Carrie Kendall
  • 11,124
  • 5
  • 61
  • 81
Nikesh Jauhari
  • 245
  • 2
  • 8
  • 1
    I can't understand your question. Are you executing an external process inside your java app that starts another java app? – jfcorugedo Apr 21 '15 at 16:20
  • 1
    If you start some code from a jar you've loaded via a class loader, the system properties are the same. Maybe show us how you "execute another java jar". – JP Moresmau Apr 21 '15 at 16:22

1 Answers1

0

If you invoque a main method inside your java application you won't start a new Java application.

In that case, you're executing a static method, just like any other static method, so the current directory is the same as the working directory of your current Java application.

If you're looking for a way to execute a java application inside an existing Java application you have to create another process.

An example:

    List<String> command = new ArrayList<String>();
    command.add("java -jar xxxxx.jar");
    command.add("argument to Main method");
    command.add("another argument to Main method");

    ProcessBuilder builder = new ProcessBuilder(command);

    File workingDirectory = new File("/myworkingdirectory");
    builder.directory(workingDirectory);

    Process process = builder.start();
jfcorugedo
  • 9,793
  • 8
  • 39
  • 47