简体   繁体   English

如何从外部存储中读取属性文件

[英]how to read property files from external storage

I have a jar file that I run from the console.我有一个从控制台运行的 jar 文件。 In the program itself, I have to read data from the property file, which should be in the same folder as my jar file.在程序本身中,我必须从属性文件中读取数据,该文件应该与我的 jar 文件位于同一文件夹中。 How can i do this?我怎样才能做到这一点?

my code which does not work correctly:我的代码无法正常工作:

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;
    }
}

Note that the way you have coded above requires a system property to mark the file to load, passed as:请注意,您在上面编码的方式需要一个系统属性来标记要加载的文件,传递为:

java -Dapp.properties=somefile.properties

If you intended a file called "app.properties" this requires a change to the declaration of propPath without System.getProperty如果您想要一个名为“app.properties”的文件,则需要更改propPath的声明而不使用System.getProperty

Your file handling should use try with resources to clean up afterwards with automatic close, and not hide any exception:您的文件处理应该使用 try 和资源在之后通过自动关闭进行清理,而不是隐藏任何异常:

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

You could provide default property values after exception, or handle by add throws IOException to the method, or append code to adapt as a runtime exception so that is is reported:您可以在异常之后提供默认属性值,或者通过将throws IOException添加到方法来处理,或者 append 代码以适应运行时异常,以便报告:

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

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

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