16 June 2008

Detect OS in Java

I realize we're still sidetracked from the Jena tutorial, more will be forthcoming. This is a small part of the next section where we are going to be building a log utility for our Jena web service.

For today here is a quick way to determine the operating system in Java. This is effective for putting a path to your file writes.

First set your os.name to a String. See the link for an entire list of what you can get back. We're not going to be looking for a very specific OS here, just check if it's Windows or not.

String osName = system.getProperty("os.name");


That is pretty much it, you can write out your value now to see what you get. Here is a quick way of creating a path to a file based on your os.

String filePath = osName.toUpperCase().indexOf("WINDOWS") == 0 ? "x:/"
        : "/lin/ux/Path/";


I used the ternary operation there to keep it quick. The above statement basically says "Does our osName in all caps have the string WINDOWS in it? yes? make the path x:/. no? make the path /lin/ux/Path."

You can do whatever you want once you have your os depending on what you're looking for.

1 comments:

vlad said...

There is no class "system". It should be "System".