Java – the best way to handle nuances for different platforms

cross platformjava

I'm working on a normal Java/SWT desktop application I'm planning on distributing to the three primary PC platforms (Windows, OSX, Linux). Obviously, there are slight differences between them, mainly having to do with files.

What's the best way to keep those differences separate? I'm thinking three different SVN branches (win, osx, linux), and trunk for development, but then how do I update the branches without overwriting the differences? Do I need to define a platform constant instead at compile time?

And then, of course, there are different versions of libraries (i.e. SWT in my case). How should those be handled? Where should I keep the compiled byte-code ".jars" files?

Best Answer

For the example you gave (file paths), you should use a configuration file. You can have one for each platform, or one big one with settings for all platforms. I'd lean toward the first option, because then you can just use that one file and all the paths would be set. Java has a rich set of methods to construct platform independent file paths; use things like File.separator rather than \.

Generally in Java you don't need to have separate projects for separate platforms - that's why the JVM! Use specific components for only those parts of the application that are platform specific. In my experience, I have not seen anything in Java intself that needs to change for different platforms. Interacting with the filesystem is trickier, but there are ways around that as described above. That being said, you should still test on the platforms you intend to deploy on to be sure that everything does work - sometimes there are subtle differences in JVMs for specialized applications.

My recommendation for jars and other platform specific components is to have a directory structure look something like this in your VCS:

/src
/lib
   linux/
      jars/
      config/
   windows/
      jars/
      config/

Then in your build scripts, only include the folder you need for the platform you're building for. I'd include the folder as lib in your build, so for a Linux build you'd end up with (as a suggestion):

/
*yourjar*
*launchfiles*
/lib
   jars/
   config/

Zip that whole thing up and unzip it where you want to install. That will avoid having to specify paths more than once in code at the expense of a slighly more complicated build process. You could probably put that in a windows installer, too.

Related Topic