在Grails中放置文本文件的位置,以及如何获取路径
我需要在.txt文件中读入一个groovy类,以便逐行查询它。 但是我不确定我在grails应用程序中放入了什么文件夹,以及如何获取它的路径?
到目前为止,我已尝试将其放在src
下,也放在新的文件夹web-app/txt
我已经尝试了以下内容来阅读它
fileIn = new File('/lexicon.txt').text
和
fileIn = new File('txt/lexicon.txt').text
无济于事。
任何身体有任何指针?
Grails是一个Java Web应用程序,因此它将被编译成一个sigle文件.war
,里面包含所有文件/类/等。 大多数Web容器都会解压缩,但是没有任何保证,因此使用File
将此文件作为文件访问并不是一个好主意。
顺便说一句,您可以将文件放入grails-app/conf
,在这种情况下,它将被放入classpath
,您将能够通过以下方式访问它:
InputStream lexicon = this.class.classLoader.getResourceAsStream('lexicon.txt')
您也可以将此文件放入子目录,例如grails-app/conf/data
并将其加载为***.getResourceAsStream('data/lexicon.txt')
你可以把你的文件放在web-app /
例:
web-app/lexicon.txt
然后在您的控制器或服务中使用grailsApplication:
class MyService { def grailsApplication public myMethod() { File myFile = grailsApplication.mainContext.getResource("lexicon.txt").file } }
希望这可以帮助
您可以使用Spring的资源加载来访问该文件。 使用此方法,您可以从Spring bean访问该文件,这意味着Grails可以将资源自动assembly到其工件中。
请参阅以下步骤示例
- 将文件放在
grails-app/conf/
。 - 在
src/groovy
一个资源持有者类 - 在
grails-app/spring/resources.groovy
中将资源持有者添加为Spring bean - 然后自动assembly并在任何需要的地方使用资源
第2步:
package resource import org.springframework.core.io.Resource class ResourceHolder { Resource lexicon }
第3步:
beans = { lexiconHolder(resource.ResourceHolder) { lexicon = 'classpath:lexicon.txt' } }
步骤4:
class AnyGrailsService { def lexiconHolder void aMethodUsingTheLexicon() { File lexicon = lexiconHolder.lexicon.file /* Do stuff with the lexicon */ }
在Grails 2中,您可以使用Grails资源定位器
class MyService { def grailsResourceLocator myMethod() { def fileIn = grailsResourceLocator.findResourceForURI('/txt/lexicon.txt').file } }
方便提示:要在Spock中模拟它,请使用GroovyPageStaticResourceLoader
@TestFor(MyService) class MyServiceSpec extends Specification { def setup() { service.grailsResourceLocator = Mock(GroovyPageStaticResourceLocator) } }