簡體   English   中英

如何從外部存儲中讀取屬性文件

[英]how to read property files from external storage

我有一個從控制台運行的 jar 文件。 在程序本身中,我必須從屬性文件中讀取數據,該文件應該與我的 jar 文件位於同一文件夾中。 我怎樣才能做到這一點?

我的代碼無法正常工作:

public class ReadProperties {
    String propPath = System.getProperty("app.properties");

    private String message;
    private String userName;

    ReadProperties() {
        readProperties();
    }

    private void readProperties() {
        final FileInputStream in;
        try {
            in = new FileInputStream(propPath);
            Properties myProps = new Properties();
            myProps.load(in);
            message = myProps.getProperty(Constants.MESSAGE);
            userName = myProps.getProperty(Constants.USERNAME);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getMessage() {
        return message;
    }

    public String getUserName() {
        return userName;
    }
}

請注意,您在上面編碼的方式需要一個系統屬性來標記要加載的文件,傳遞為:

java -Dapp.properties=somefile.properties

如果您想要一個名為“app.properties”的文件,則需要更改propPath的聲明而不使用System.getProperty

您的文件處理應該使用 try 和資源在之后通過自動關閉進行清理,而不是隱藏任何異常:

try (FileInputStream in = new FileInputStream(propPath)) {
    // load here
}

您可以在異常之后提供默認屬性值,或者通過將throws IOException添加到方法來處理,或者 append 代碼以適應運行時異常,以便報告:

catch (Exception e) {
    throw new UncheckedIOException(e);
}
       

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM