10

Is it possible to get the file name which is being executed. Like e.g. If i am running a Jar file, and inside i want to add code functionality that can detect the file name so that if this jar is renamed, code should be able to detect that.

Is there any possibility of doing this without scanning the files in current directory?

Johnydep
  • 6,027
  • 20
  • 57
  • 74
  • actually i don't want to detect this using current PID, wondering if there is some java's bulit in support for this? – Johnydep Jan 12 '12 at 09:33
  • Related: http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file – jalopaba Jan 12 '12 at 09:57

2 Answers2

5

Try this:

String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");

http://www.rgagnon.com/javadetails/java-0300.html

http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getProtectionDomain()

http://docs.oracle.com/javase/7/docs/api/java/security/ProtectionDomain.html

Afshin Moazami
  • 2,092
  • 5
  • 33
  • 55
Aleja_Vigo
  • 970
  • 7
  • 12
  • thanks although not in all scenarios but it does work partially, Is there any documentation of the methods defined above? – Johnydep Jan 12 '12 at 09:50
-1

you could check if System.getEnv() has some value indicating which file was invoked

Hachi
  • 3,237
  • 1
  • 21
  • 29