Berouminum Berouminum - 4 months ago 11
Java Question

Can't return a value from a property file - Java

im currently trying to implement a config in my program.
I've already managed to create and also read the file but I still have trouble returning a value with a "double - method".

Creating the file:

public void setDefaultConfig()
{
Properties prop = new Properties();
OutputStream output = null;

try {

output = new FileOutputStream("config.properties");

prop.setProperty("window_close_speed", "5000");

prop.store(output, null);

} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
}


Reading and trying to return the speed:

public double retSpeed()
{
Properties prop = new Properties();
InputStream input = null;

try {

input = new FileInputStream("config.properties");

prop.load(input);

double windowSpeed = Double.parseDouble(prop.getProperty("window_close_speed"));

} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();

}
}
}
}


For some reason I can't "return windowSpeed;". Eclipse either complains about "windowSpeed cannot be resolved to a variable" or "this method must return a result of type double". windowSpeed's value is 5000.00 and seems to be completely fine when returning it with System.out.println();

Any ideas ?

Thanks for reading

Answer

If you're going to return a value from a method, you need a return statement -- in all of the blocks of code that are potentially executed; the "normal" execution flow and also the flow where you catch exceptions:

public double retSpeed() {
    Properties prop = new Properties();
    InputStream input = null;

    try {

        input = new FileInputStream("config.properties");
        prop.load(input);
        return Double.parseDouble(prop
                .getProperty("window_close_speed"));

    } catch (IOException ex) {
        ex.printStackTrace();

        // You need to return something here,
        // although it would probably be better to just
        // throw new RuntimeException(ex);
        // in case the property file cannot be read.
        return -1.0d;
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}