Where to put a text file in Grails, and how to get the path

前端 未结 4 1072
感动是毒
感动是毒 2020-12-13 09:41

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

4条回答
  •  佛祖请我去吃肉
    2020-12-13 10:23

    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

    1. Place the file in grails-app/conf/.
    2. Make a resource holder class in src/groovy
    3. Add the resource holder as a Spring bean in grails-app/spring/resources.groovy
    4. Then autowire and use the resource wherever you need it

    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 */
        }
    

提交回复
热议问题