繁体   English   中英

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

[英]How to load properties file into 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打印。 谁能让我知道上面代码中的错误是什么?

InputStream inputStream = new FileInputStream(propFile);

而已...

因为

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

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

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

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

String propFile  = "./connection.properties";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM