如何将属性文件加载到Java中?

时间:2019-03-29 11:26:31

标签: java

我正在尝试将属性文件加载到Linux目录中存在的Java中。 connection.properties:

hiveDriver=HiveDriver
hiveServer=ip-1-2-1-1.
hivePort=123
hiveUser=huser
hivePassword=etl123
gpDriver=org.postgresql.Driver
metaStoreUrl=metaurl
port=5432
metaUser=devusr
metaPassword=abcdefg
gpAnalyticsServer=1.2.3.4.5
gpUser=gpuser
gpPassword=09987665

代码:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

try {
    Properties props = new Properties();
    String propFile  = "/home/devuser/connection.properties";
    InputStream inputStream = StartCount.class.getClassLoader().getResourceAsStream(propFile);
    if(inputStream != null) {
        props.load(inputStream);
    }
    String hiveDriver           = props.getProperty("hiveDriver");
    String hiveServer           = props.getProperty("hiveServer");
    String hivePort             = props.getProperty("hivePort");
    String hiveUser             = props.getProperty("hiveUser");
    String hivePassword         = props.getProperty("hivePassword");
    String gpDriver             = props.getProperty("gpDriver");
    String hiveMetaStoreServer  = props.getProperty("hiveMetaStoreServer");
    String port                 = props.getProperty("port");
    String hiveMetaUser         = props.getProperty("hiveMetaUser");
    String hiveMetaPassword     = props.getProperty("hiveMetaPassword");
    String gpAnalyticsServer    = props.getProperty("gpAnalyticsServer");
    String gpUser               = props.getProperty("gpUser");
    String gpPassword           = props.getProperty("gpPassword");
    System.out.println(hiveDriver)      ;
    System.out.println(hiveServer);
    System.out.println(hivePort);
    System.out.println(hiveUser);
    System.out.println(hivePassword);
    System.out.println(gpDriver);
    System.out.println(hiveMetaStoreServer);
    System.out.println(port);
    System.out.println(hiveMetaUser);
    System.out.println(hiveMetaPassword);
    System.out.println(gpAnalyticsServer);
    System.out.println(gpUser);
    System.out.println(gpPassword); 
} catch(Exception e) {
    e.printStackTrace();
}

我正在从保存“ connection.properties”的同一位置提交jar。 运行代码时,我从println语句看到null打印。谁能让我知道我在上面的代码中犯了什么错误?

3 个答案:

答案 0 :(得分:1)

InputStream inputStream = new FileInputStream(propFile);

就这样...

因为

StartCount.class.getClassLoader().getResourceAsStream(propFile) != propFile

答案 1 :(得分:0)

使用NIO2,您可以加载文件(如果您具有读取权限),然后将其转换为InputStream,如下所示:

Path path = Paths.get("/home/devuser/connection.properties");
InputStream str = Files.newInputStream(path);

答案 2 :(得分:0)

您的问题是路径,请尝试替换它:

data-fancybox="group_<?=$r['reference_id'];?>"