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

标签 java groovy readfile

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

#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) {
                }
            }
        }
    }

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

最佳答案

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

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() 来应用值即可。

关于java - 如何使用groovy读取文件并将其内容存储为变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34927407/

相关文章:

java - 对象类继承

Java 递归超过 2 个参数和两个方向

class - 如何在类中使用 Jenkins 插件?

Jenkins 管道电子邮件通知与电子邮件中控制台输出的某些部分

c++ - 串行端口 : ReadFile and CloseHandle

c# - 使用c#从文档中获取纯文本

java - Spring 5 FluxSink执行fluxSink.next时不发送数据

java - 当尝试将 1 到 n 之间的所有数字加在一起时,代码不会返回总和

java - 从 Java/Groovy 运行复合 shell 命令

Python读取.txt文件->列表