有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用groovy读取文件并将其内容存储为变量?

我正在寻找groovy特有的方法来读取文件并将其内容存储为不同的变量。我的属性文件示例:

#Local credentials:
postgresql.url = xxxx.xxxx.xxxx
postgresql.username = xxxxxxx
postgresql.password = xxxxxxx
console.url = xxxxx.xxxx.xxx

目前,我正在使用以下java代码读取文件并使用变量:

  Properties prop = new Properties();
  InputStream input = null;

  try {
            input = new FileInputStream("config.properties");
            prop.load(input);
            this.postgresqlUser = prop.getProperty("postgresql.username")
            this.postgresqlPass = prop.getProperty("postgresql.password")
            this.postgresqlUrl = prop.getProperty("postgresql.url")
            this.consoleUrl = prop.getProperty("console.url")

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }
        }
    }

我的同事建议使用groovy方法来处理这个问题,并提到了流,但我似乎找不到关于如何在单独的变量中存储数据的更多信息,到目前为止,我所知道的是def text = new FileInputStream("config.properties").getText("UTF-8")可以读取整个文件并将其存储在一个变量中,但不能单独存储。任何帮助都将不胜感激


共 (2) 个答案

  1. # 2 楼答案

    如果您愿意使属性文件键和类属性遵守命名约定,那么可以非常轻松地应用属性文件值。下面是一个例子:

    def config = '''
    #Local credentials:
    postgresql.url = xxxx.xxxx.xxxx
    postgresql.username = xxxxxxx
    postgresql.password = xxxxxxx
    console.url = xxxxx.xxxx.xxx
    '''
    
    def props = new Properties().with {
        load(new StringBufferInputStream(config))
        delegate
    }
    
    class Foo {
        def postgresqlUsername
        def postgresqlPassword
        def postgresqlUrl
        def consoleUrl
    
        Foo(Properties props) {
            props.each { key, value ->
                def propertyName = key.replaceAll(/\../) { it[1].toUpperCase() }
                setProperty(propertyName, value)
            }
        }
    }
    
    def a = new Foo(props)
    
    assert a.postgresqlUsername == 'xxxxxxx'
    assert a.postgresqlPassword == 'xxxxxxx'
    assert a.postgresqlUrl == 'xxxx.xxxx.xxxx'
    assert a.consoleUrl == 'xxxxx.xxxx.xxx'
    

    在本例中,通过删除“.”来转换属性键并将下面的字母大写。所以postgresql.url变成了postgresqlUrl。然后,只需迭代键并调用setProperty()来应用值