metrotyranno
metrotyranno

Reputation: 23

Testing if file exists but get nullpointexception

public class ReadConfig  {

    private File configFile; 

    public boolean testConfig(){
        if(Utils.isWindows()){
            File configFile = new File("C:/config.properties");
        }
        else{
            File configFile = new File("/config.properties");
        }
        if(configFile.exists() && !configFile.isDirectory()){
            System.out.println(configFile + "found!");
            return true;
        }
        else{
            try {
                configFile.createNewFile();
                System.out.println(configFile + "created!");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        }
    }
}

This gives back a null point exception at the following line

if(configFile.exists() && !configFile.isDirectory()){

It seems to me that it should return false, why would it throw a NullPointerException?

Upvotes: 1

Views: 35

Answers (1)

ebo
ebo

Reputation: 2747

The problem is that the statements in your if and else branch initialize a new variable called configFile, instead of using the field. Removing File should do the trick, e.g.:

if(Utils.isWindows()){
    configFile = new File("C:/config.properties");
} else {
   configFile = new File("/config.properties");
}

Upvotes: 3

Related Questions