I need to read in a .txt file into a groovy class in order to interrogate it line by line. But I am not sure what folder I put it into in my grails app, and how to get the
In Grails 2, you can use the Grails Resource Locator
class MyService {
def grailsResourceLocator
myMethod() {
def fileIn = grailsResourceLocator.findResourceForURI('/txt/lexicon.txt').file
}
}
Handy tip: to mock this in Spock, use GroovyPageStaticResourceLoader
@TestFor(MyService)
class MyServiceSpec extends Specification {
def setup() {
service.grailsResourceLocator = Mock(GroovyPageStaticResourceLocator)
}
}
You can use Spring's resource loading to access the file. With this method you can access the file from a Spring bean, which means Grails can autowire the resource in to its artifacts.
See below for the following steps examples
grails-app/conf/
.src/groovy
grails-app/spring/resources.groovy
Step 2:
package resource
import org.springframework.core.io.Resource
class ResourceHolder {
Resource lexicon
}
Step 3:
beans = {
lexiconHolder(resource.ResourceHolder) {
lexicon = 'classpath:lexicon.txt'
}
}
Step 4:
class AnyGrailsService {
def lexiconHolder
void aMethodUsingTheLexicon() {
File lexicon = lexiconHolder.lexicon.file
/* Do stuff with the lexicon */
}
You can put your file under web-app/
Example:
web-app/lexicon.txt
And then in your controller or service use grailsApplication:
class MyService {
def grailsApplication
public myMethod() {
File myFile = grailsApplication.mainContext.getResource("lexicon.txt").file
}
}
Hope this helps
Grails is a Java Web Application, so it will be compiled into a sigle file .war
, with all files/classes/etc inside. Most Web containers do unpack war
, but there are no any guaranteee, so it's not a good idea to use File
to access this file as a file.
Btw, you can place your file into grails-app/conf
, at this case it will be placed into classpath
, and you'll be able to access it by using:
InputStream lexicon = this.class.classLoader.getResourceAsStream('lexicon.txt')
You could also put this file into a subdirectory, like grails-app/conf/data
and load it as ***.getResourceAsStream('data/lexicon.txt')