Java check OS dependancy

As you are aware java is multi-platform so it’s nice and easy for developers as we have to code only once and should in theory always work on all platforms apart from when you require to interact with the System it self at that point you need to tell Java what system it is and what to do for each one.

I my case the calculator contain a config file and also a history file and for us to be able to access those file whether it is to read or write Java needs to know where it is.

This is how I achieved it and it works nicely, I even discovered today that Windows 8 stores their application data in a different PATH than its predecessors.

Let me show you how.

Created a new class..

public class SystemPath {
}

Inside the class created all the required strings and initialised their value, I also changed the “os.name” to lower case to insure there will be no typo issues.


static String configFile = "calculatorOrange.conf";
static String homeDir = System.getProperty("user.home");
static String osName = System.getProperty("os.name").toLowerCase();
static String history = "CalculatorHistory.html";
static String workingDir = null;
static File historyFile = null;

For each instant I will create a returnable variable in this case workingDir and historyFile will both return a variable that I use in my main class.

First I will show you the workingDir and how it’s constructed.

public static String workingDir() throws IOException {
if (osName.indexOf("nux") >= 0 || osName.indexOf("nix") >= 0) {
workingDir = (homeDir + "/" + ".config" + "/" + configFile);
} else if (osName.equals("windows xp")) {
workingDir = (homeDir + "\\Application Data\\" + configFile);
} else if (osName.equals("windows 7")) {
workingDir = (homeDir + "\\Application Data\\" + configFile);
} else if (osName.equals("windows 8")) {
workingDir = (homeDir + "\\Local Settings\\" + "\\Application Data\\" + configFile);
} else if (osName.indexOf("mac") >= 0){
workingDir = (homeDir + "/Library/" + configFile);
} else {
workingDir = (homeDir + configFile);
}
return workingDir;
}

I have the same construction for the historyFile that I call every time I need to save a new record to the file.

public static File historyFile() throws IOException {
if (osName.indexOf("nux") >= 0 || osName.indexOf("nix") >= 0) {
historyFile = new File(homeDir + "/" + ".config" + "/"+ history);
} else if (osName.equals("windows xp")) {
historyFile = new File(homeDir + "\\Application Data\\" + history);
} else if (osName.equals("windows 7")) {
historyFile = new File(homeDir + "\\Application Data\\" + history);
} else if (osName.equals("windows 8")) {
historyFile = new File(homeDir + "\\Local Settings\\" + "\\Application Data\\" + history);
} else if (osName.indexOf("mac") >= 0){
historyFile = new File(homeDir + "/Library/" + history);
} else {
historyFile = new File(homeDir + history);
}
return historyFile;
}
}

And that is all for now folks.