0

How to reference directories correctly when launching a .jar from a batch file?

I am trying to launch a jar file from a .bat . One of the first things my code does is open and read from a file. I reference the file like this:

final ArrayList<EmailAccount> emailList = FileIO.getListOfAccountsFromFile(".\\EmailList\\list.txt");

Everything works fine if the batch file is in the same directory as my jar. HOWEVER, if I put my batch file somewhere else and try to run it (like i plan to have it work), the program thinks that I'm trying to reference a file that is in the

".bat directory"\EmailList\list.txt

instead of

".jar directory"\EmailList\list.txt

and comes up with a fileNotFoundException.

Is there any way that I can run my batch file from a different directory while correctly referencing files in relation to the jar without hard coding in the jar's file path?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

1 Answers1

0

You can ask the JVM about the location of a given class. If you know it is inside the jar you refer to, then you can then extract the location of the jar file, and then construct your file objects relative to that.

See https://stackoverflow.com/a/320595/53897 for details about

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
Community
  • 1
  • 1
Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347