Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the path of the running script in groovy?

Tags:

groovy

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?

like image 544
Dan Woodward Avatar asked Jul 22 '09 04:07

Dan Woodward


People also ask

How do I set the path of a file in groovy?

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.

How do I view groovy files?

Check the version of Groovy in a projectFrom the main menu select File | Project Structure Ctrl+Alt+Shift+S .

How do I change groovy directory?

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.


2 Answers

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 
like image 70
seansand Avatar answered Oct 14 '22 04:10

seansand


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.

like image 31
M. Justin Avatar answered Oct 14 '22 05:10

M. Justin