在 Grails 中放置文本文件的位置以及如何获取路径 [英] Where to put a text file in Grails, and how to get the path
问题描述
我需要将 .txt 文件读入一个 groovy 类,以便逐行查询它.但我不确定我把它放在我的 grails 应用程序中的哪个文件夹中,以及如何获取它的路径?
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 path to it?
到目前为止,我已经尝试将它放在 src
下以及一个新文件夹 web-app/txt
So far I have tried placing it under src
and also in a new folder web-app/txt
我已经尝试了以下内容来阅读它
and I have tried the the following to read it in
fileIn = new File('/lexicon.txt').text
和
fileIn = new File('txt/lexicon.txt').text
无济于事.
任何身体有任何指针?
推荐答案
Grails 是一个 Java Web 应用程序,所以它会被编译成一个单独的文件 .war
,包含所有文件/类/等里面.大多数 Web 容器确实会解包 war
,但没有任何保证,因此使用 File
将此文件作为文件访问并不是一个好主意.
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.
顺便说一句,你可以把你的文件放到grails-app/conf
中,在这种情况下,它会被放到classpath
中,你就可以访问它了通过使用:
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')
您也可以将此文件放入一个子目录中,例如 grails-app/conf/data
并将其加载为 ***.getResourceAsStream('data/lexicon.txt')代码>
You could also put this file into a subdirectory, like grails-app/conf/data
and load it as ***.getResourceAsStream('data/lexicon.txt')
这篇关于在 Grails 中放置文本文件的位置以及如何获取路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!