0
votes

I am running into a bit of a strange error here when creating a new file object with a GStringImpl. If I create a new File (and then list files in that path) with a GStringImpl, I get an empty array, and no error, however if I just a normal string, I get a list of files... While that makes sense in a way I would think that there would be an error somewhere.

Example:

def thisIsAListOfFiles = new File("/absolute/fs/mount/point").listFiles()

def gString = "${StaticClass.propertyStringThatIsAnAbsoluteFilePath}"
def notAListOfFiles = new File(gString).listFiles()

Any thoughts on what is going on here? Is this the expected behavior?

More info:

  • Groovy Version: 2.1.3
  • Grails version: 2.2.2 (this is within a grails app of course)
  • Java version: OpenJDK Runtime Environment (IcedTea 2.3.9)

I start out with a properties file with a bunch of properties like this

com.mycompany.property = "/absolute/directory/path"

Because I cant easily inject grailsApplication into non grails classes (anything in /src/groovy for instance) I inject grailsApplication into bootstrap, and use groovy config slurper to read the properties file from the classpath and set then as static string values in a groovy class Config.groovy. That groovy class then has the static variables of all of the properties I need anywhere within the application.

Note: this is not an issue reading the properties files, or anything along those lines. I log the Config.filePathProperty right before the new File(var).listFiles() occurs and that value is set properly.

1

1 Answers

1
votes

I'm pretty sure your static path is set incorrectly. I ran the following code as a test:

String path = '/etc/'

print "String ($path): "
println(new File(path).listFiles().size())

def gpath = "${path}"

print "GString ($gpath): "
println(new File(gpath).listFiles().size())

class Foo {
    static String path = '/etc/'
}

print "GString static ($Foo.path): "
println(new File("${Foo.path}").listFiles().size())

And got this result (obviously your file count will vary):

String (/etc/): 122
GString (/etc/): 122
GString static (/etc/): 122

The only time I saw a null result was when the path was invalid, for example:

assert new File("does-not-exist").listFiles() == null

One thing you could do would be to eliminate the GString, which is unnecessary in your example:

def notAListOfFiles = new File(StaticClass.propertyStringThatIsAnAbsoluteFilePath).listFiles()

But I'm sure you'll find a typo in the variable or file path, or another similar issue.