chrisjlee chrisjlee - 3 years ago 243
Groovy Question

Groovy - check system env exists otherwise use a default path?

I'm super new to java and groovy. So i need some more explaining for these concepts. I come from a JavaScript / PHP background and i'm a bit lost.

Problem



In my gradle build, i've got to compile these jars. I also have a base of users on windows / mac users which some of them have set the environment variables and some haven't. The windows users, most of them, aren't able to set their environment variables because of permissions issues which require administrative access. I work at a big company and it's not easy getting admin access.

How does one default paths if it's
nil
?



How does one default if their system path isn't defined to use a hard-coded path?

Additionally, How does one check if that path exists?

E.g. Here's my code that i've renamed some of my variables:

task build {
def root = System.getenv.FOO_HOME ?: 'C:/foo/foo/'
def paths = [
root + 'foo.jar',
root + 'foo2.jar',
root + 'foo4.jar',
root + 'foo3.jar'
]

// I'm lost here. I don't know how to detect if that path exists for a that?
/* psuedo code */
def validPaths = paths.map(item -> new Path(item))
}


Thanks in advance.

Answer Source

To convert a string to a Path use java.nio.file.Paths. Paths.get() will return you a Path object, except even that won't let you know if the file exists on disk or not.

So I would convert the path to a File, then ask that if it exists.

import java.nio.file.Paths
Paths.get( "~/NotThere").toFile().exists()

In a list I'd separate out these two operations like so:

// First, make an array of File objects
def asFiles = paths.collect( { currentString -> Paths.get( currentString ).toFile() } )

// now remove all the File objects that don't exist
def onlyExistingFiles = asFiles.findAll { currentPath -> currentPath.exists() }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download