将文件加载到java.util.Properties中的单行程序

时间:2015-07-28 12:47:05

标签: java nashorn

我有许多包含凭据和其他配置的java属性文件,我正在寻找最简洁的代码来加载Nashorn的javascript和Java。

到目前为止,我还剩2行:

credentials = new java.util.Properties();
credentials.load(new java.io.FileInputStream("credentials.properties"));

我已尝试过这种明显的合并,但它在Nashorn中无效:

credentials = (new java.util.Properties()).load(new java.io.FileInputStream("credentials.properties"));

这些可以合并成一行吗?如果可读性受到严重影响并不重要。

3 个答案:

答案 0 :(得分:1)

我认为它应该可行,至少在Java中是这样的:

    (credentials = new java.util.Properties()).load(new java.io.FileInputStream("credentials.properties"));

答案 1 :(得分:1)

如果你想使用Optional和lambdas非常不经常地使用Java-8风格,你可以试试这个

Properties credentials=Optional.of(new Properties()).map(p->{try{p.load(new FileInputStream("credentials.properties"));}catch(IOException e){}return p;}).get();

(更长,但更具可读性的换行版本)

Properties credentials = Optional.of(new Properties())
    .map(p -> {
             try
             {
                p.load(new FileInputStream("credentials.properties"));
             }
             catch (IOException ex) {}
             return p;
         })
    .get();

<强>更新

没有try / catch它会成为java:

Properties credentials = Optional.of(new Properties()).map(p -> { p.load(new FileInputStream("credentials.properties")); return p; }).get();

和Nashorn js:

var credentials = java.util.Optional.of(new java.util.Properties()).map(function(p) { p.load(new java.io.FileInputStream("credentials.properties")); return p;}).get();

答案 2 :(得分:0)

最简单,最安全的解决方案是使用实用程序方法引入一个间接层:

public static Properties loadProperties(File file)
{
    Properties props = new Properties();
    try (FileInputStream fis = new FileInputStream(file))
    {
        props.load(fis);
    }
    catch (IOException ioex) { ioex.printStackTrace(); }
    return props;
}

Properties credentials = loadProperties(new File("credentials.properties"));

JS的等价物是(没有try/catch):

function loadProperties(file) {
    var props = new java.util.Properties();
    props.load(new java.io.FileInputStream(file));
    return props;
}

通过添加try语句,您还可以轻松捕获I / O错误。