how to read property files from external storage

Viewed 31

I have a jar file that I run from the console. In the program itself, I have to read data from the property file, which should be in the same folder as my jar file. 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;
    }
}
1 Answers

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

Your file handling should use try with resources to clean up afterwards with automatic close, and not hide any exception:

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:

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