Writing Operating System-Dependent Code

Problem

You need to write code that depends on the underlying operating system.

Solution

Again, don’t do this. Or, if you must, use System.properties.

Discussion

While Java is designed to be portable, there are some things that aren’t. These include such variables as the filename separator. Everybody on Unix knows that the filename separator is a slash character ( / ) and that a backwards slash or backslash ( \ ) is an escape character. Back in the late 1970s, a group at Microsoft was actually working on Unix -- their version was called Xenix, later taken over by SCO -- and the people working on DOS saw and liked the Unix filesystem model. MS-DOS 2.0 didn’t have directories, it just had “user numbers” like the system it was a clone of, Digital Research CP/M (itself a clone of various other systems). So the Microsoft folk set out to clone the Unix filesystem organization. Unfortunately, they had already committed the slash character for use as an option delimiter, for which Unix had used a dash (-). And the PATH separator (:) was also used as a “drive letter” delimiter, as in C: or A:. So we now have commands like this:

System

Directory list command

Meaning

Example PATH setting

Unix

ls -R /

Recursive listing of /, the top-level directory

PATH=/bin:/usr/bin

DOS

dir/s \

Directory with subdirectories option (i.e., recursive) of \, the top-level directory (but only of the current drive)

PATH=C:\windows;D:\mybins

Where ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.