0

I have an existing method that gets properties from a fixed location. This method also allows me to specify an override to use a different properties file. I want to be able to specify a file that is on the classpath while preserving the current functionality. How would I modify this to achieve this functionality?

protected Properties getProperties(String pathToPropertiesFile) throws IOException {
    if (pathToPropertiesFile == null) {
        pathToPropertiesFile = "/etc/machineProperties.properties";
    }

    FileInputStream inputStream = new FileInputStream(pathToPropertiesFile);

    Properties props = new Properties();
    props.load(inputStream);
    return props;
}

All the IO utilities I have found so far work for only files on the classpath or files with absolute paths.

Rylander
  • 19,449
  • 25
  • 93
  • 144

1 Answers1

1

To load a text file that's on your classpath. Taken from here for more context.

InputStream in = this.getClass().getClassLoader()
                                .getResourceAsStream("SomeTextFile.txt");
Community
  • 1
  • 1
KyleM
  • 4,445
  • 9
  • 46
  • 78
  • This returns null if you pass the absolute path of a resource that is not on the classpath. – Rylander Nov 20 '14 at 22:12
  • @MikeRylander Yes, that's what it says in the Javadoc https://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#getResourceAsStream(java.lang.String) . Is that a problem or are you just making a note of it? – KyleM Nov 20 '14 at 22:32
  • I need to preserve the functionality that currently exists around reading files that are NOT on the classpath. – Rylander Nov 20 '14 at 23:21
  • @MikeRylander If the getResourceAsStream returns null, then call your existing getProperties() method. You might need to edit your question if you need more assistance...I already answered your question as it was asked. – KyleM Nov 21 '14 at 15:47