Dynamically Find Java Path

Yesterday I needed to execute a jar file from within ColdFusion, so I was planning to use cfexecute to execute the java executable and then pass in the jar file as an argument. This worked fine, but the trouble occured when I had to run this same code on a different server where the java path was different. So I started researching to find a way to dynamically insert the java path that ColdFusion uses and then the code would run on any CF server without having to modify the java path. I came up with this code:

<cfset javaSystem = createObject("java", "java.lang.System") />
<cfset javaPath = javaSystem.getProperty("java.home") & "/bin/java.exe" />

So that code will dynamically discover the java path on any server. I should note (even though it's obvious) that the second line appends ".exe" to the end of the path, and that will only work on Windows servers. I just tried the code on my Linux VPS server and it would still work as long as you remove the ".exe". I'm assuming the same is true for a Mac, but I don't have one to test with.

For those that are looking to see how to use this in a cfexecute, here's the code:

<cfexecute
   name="#pathToJavaExe#"
   arguments="-jar #expandPath('.')#/myJarFile.jar"
   timeout="20" />

Comments
BlogCFC was created by Raymond Camden. This blog is running version 5.9. Contact Blog Owner