使用Groovy从属性文件中获取值

 灰太狼老婆红太狼_715 发布于 2023-02-07 10:53

如何使用Groovy从属性文件中获取值?

我需要一个属性文件(.properties),它将文件名作为键,并将其目标路径作为值.我需要在运行时解析密钥,具体取决于需要移动的文件.

到目前为止,我能够加载它看起来的属性,但不能从加载的属性"获取"值.

我提到了线程:groovy:如何访问属性文件?以下是我到目前为止的代码片段

def  props = new Properties();
File propFile = 
          new File('D:/XX/XX_Batch/XX_BATCH_COMMON/src/main/resources/patchFiles.properties')
props.load(propFile.newDataInputStream())
def config = new ConfigSlurper().parse(props)
    def ant = new AntBuilder()
    def list = ant.fileScanner {
                fileset(dir:getSrcPath()) {
                    include(name:"**/*")
                }
    }
    for (f in list) {
       def key = f.name
       println(props)
       println(config[key])
       println(config)
       def destn = new File(config['a'])

    }

属性文件现在具有以下条目:

jan-feb-mar.jsp=/XX/Test/1
XX-1.0.0-SNAPSHOT.jar=/XX/Test/1
a=b
c=d

如果我使用props.getProperty('a')或config ['a']查找,则返回正确的值.还尝试了代码:notation

但是一旦切换到使用变量"key",就像在config [key]中一样,它返回 - > [:]

我是groovy的新手,不能说我在这里失踪了什么.

3 个回答
  • 除非File是必要的,如果要加载的文件是src/main/resources或者src/test/resources文件夹或类路径,getResource()是另一种方式来解决这个问题.

    例如.

        def properties = new Properties()
        //both leading / and no / is fine
        this.getClass().getResource( '/application.properties' ).withInputStream {
            properties.load(it)
        }
    
        //then: "access the properties"
        properties."my.key"
    

    2023-02-07 10:56 回答
  • 以防万一...

    如果属性键包含点(.),请记住将键放在引号中.

    属性文件:

    a.x = 1
    

    常规:

    Properties properties ...
    
    println properties."a.x"
    

    2023-02-07 10:57 回答
  • 在我看来,你太复杂了.

    这是一个应该完成工作的简单示例:

    对于给定的test.properties文件:

    a=1
    b=2
    

    这段代码运行正常:

    Properties properties = new Properties()
    File propertiesFile = new File('test.properties')
    propertiesFile.withInputStream {
        properties.load(it)
    }
    
    def runtimeString = 'a'
    assert properties."$runtimeString" == '1'
    assert properties.b == '2'
    

    2023-02-07 10:57 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有