I'm writing a groovy script that I want to be controlled via a properties file stored in the same folder. However, I want to be able to call this script from anywhere. When I run the script it always looks for the properties file based on where it is run from, not where the script is.
How can I access the path of the script file from within the script?
Since the path changes machine to machine, you need to use a variable / project level property, say BASE_DIRECTORY, set this value according to machine, here "/home/vishalpachupute" and rest of the path maintain the directory structure for the resources being used.
Check the version of Groovy in a projectFrom the main menu select File | Project Structure Ctrl+Alt+Shift+S .
def cmd=new CommandShell() println cmd. execute("cd /d c:\\") println cmd. execute("dir") // Will be the dir of c:\ I wrote a groovy class like this once, it's a lot of experimenting and your instance can be trashed by commands like "exit" but it's possible.
You are correct that new File(".").getCanonicalPath()
does not work. That returns the working directory.
To get the script directory
scriptDir = new File(getClass().protectionDomain.codeSource.location.path).parent
To get the script file path
scriptFile = getClass().protectionDomain.codeSource.location.path
As of Groovy 2.3.0 the @SourceURI
annotation can be used to populate a variable with the URI of the script's location. This URI can then be used to get the path to the script:
import groovy.transform.SourceURI import java.nio.file.Path import java.nio.file.Paths @SourceURI URI sourceUri Path scriptLocation = Paths.get(sourceUri)
Note that this will only work if the URI is a file:
URI (or another URI scheme type with an installed FileSystemProvider), otherwise a FileSystemNotFoundException will be thrown by the Paths.get(URI)
call. In particular, certain Groovy runtimes such as groovyshell and nextflow return a data:
URI, which will not typically match an installed FileSystemProvider
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With