1

What I'm basically trying to do here, is run a .jar file which is located under

C/Users/-any user here-/appdata/Roaming/-my folder here-/-file name here-.jar

Do I somehow open a CMD and do:

cd appdata/Roaming/<Folder>
java -jar <FileName>.jar

This seems to work when I type it into CMD itself. I can't seem to make it work when running from java program.

I tried to do:

Runtime.getRuntime().exec("cd appdata/Roaming");

And I get an error that the specified directory doesn't exist.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user2098268
  • 121
  • 2
  • 2
  • 7
  • 1
    A few tips. Read (and implement) *all* the recommendations of [When Runtime.exec() won't](http://www.javaworld.com/jw-12-2000/jw-1229-traps.html). That might solve the problem. If not, it should provide more information as to the reason it failed. Then ignore that it refers to `exec` and build the `Process` using a `ProcessBuilder`. Also break a `String arg` into `String[] args` to account for arguments which themselves contain spaces. – Andrew Thompson Jul 17 '13 at 08:10
  • @AndrewThompson This seems like an answer to me instead of just a comment. – Viktor Seifert Jul 17 '13 at 08:24
  • @ViktorSeifert If the question had not already been offered a (correct) answer I might have submitted it as one. Of course, it might become the answer to the next few questions posted by the OP. ;) – Andrew Thompson Jul 17 '13 at 08:37

2 Answers2

4

Use an absolute path instead of a relative path, that should prevent the path not being found if you run from any working directory. Otherwise add it to your classpath as Nizil said.

To get the current user's name, use System.getProperty("user.name") and concatenate into your path.

user = System.getProperty("user.name");
cmd = "java -jar C/Users/" + user + "/appdata/Roaming/<folder>/<file>.jar";
Runtime.getRuntime().exec(cmd);
CrystalDuck
  • 345
  • 2
  • 13
3

You just have to add the jar's path in your classpath (don't forget to use an absolute path), and call the main method of the jar in you code. However, this solution is user-specific, as the path will be harcoded, unless you want to dive into something more tricky (How do you change the classpath within java).

Community
  • 1
  • 1
NiziL
  • 5,068
  • 23
  • 33
  • Ow boy.. That's why I typed out what I need. I'm making a Minecraft like launcher, which will launch my game which is located in appdata/Roaming from anywhere on the computer. – user2098268 Jul 17 '13 at 07:32
  • Well, if you use an absolute path, it will. But only on your computer, for your user ;) – NiziL May 02 '15 at 11:04