簡體   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