Skip to content

Instantly share code, notes, and snippets.

@ysb33r
Last active November 4, 2022 14:18
Show Gist options
  • Save ysb33r/5804364 to your computer and use it in GitHub Desktop.
Save ysb33r/5804364 to your computer and use it in GitHub Desktop.
The Groovy way to obtain a relative path given two paths.
def root= new File('/usr/share')
def full= new File('/usr/share/docs/rpm-4.4')
// Print the relative path of 'full' in relation to 'root'
// Notice that the full path is passed as a parameter to the root.
def relPath= new File( root.toURI().relativize( full.toURI() ).toString() )
@akhikhl
Copy link

akhikhl commented May 25, 2015

little error: "def relPath". Thanks for a nice snippet!

@ysb33r
Copy link
Author

ysb33r commented Jul 24, 2015

Thanks @akhikhl, I've corre ted it now.

@jgustie
Copy link

jgustie commented Jun 9, 2016

Using URI is dangerous here because of the encoding (e.g. if full were /usr/share/docs with space/rpm-4.4 you end up with docs%20with%20space/rpm-4.4). You can use the Path.relativize from Java 7 to avoid this:

def relPath = root.toPath().relativize( full.toPath() ).toFile()

@ysb33r
Copy link
Author

ysb33r commented Jul 7, 2016

@jgustie - Thx for that.

@retraut
Copy link

retraut commented Jul 6, 2020

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: java.lang.String.toPath() is applicable

@figroc
Copy link

figroc commented Jul 18, 2020

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: java.lang.String.toPath() is applicable

It is File::toPath, not String::toPath.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment