A Cross-Platform Approach to Coding

Hello folks!

Operating systems have some differences that can sometimes be anticipated and handled in code.

This OS-dependent example works for Windows 10 but not for macOS or Linux:

String classPaths = System.getProperty("java.class.path");

println(classPaths);
println();

String [] path = classPaths.split(";");   // OS-dependent Windows path separator
printArray(path);

Note:
The above code assumes a Windows environment since it uses the ; separator. On MacOS or Linux, this will fail.

A cross-platform approach using java.io.File:

import java.io.File;

// String
println(File.pathSeparator);   // Correct separator for current OS
println(File.separator);       // Correct file separator for current OS

// char
println(File.pathSeparatorChar);  // Char representation of the path separator
println(File.separatorChar);      // Char representation of the file separator

I left integrating File.pathSeparator into the split function as an exercise for the reader. :-)

The Processing Wiki has a section on Platforms that would benefit from OS-related topics for improving clarity in cross-platform development, such as those discussed and others:
https://github.com/processing/processing4/wiki/Troubleshooting#platforms

I will share in GitHub Issues (opportunities) in the future.

Season’s Greetings! - A universally cross-platform wish for the end of the year.

This should work on Windows, macOS and Linux:

// Get the OS name
String os = System.getProperty("os.name").toLowerCase();
println("Operating System: " + os);

size(500, 200, P2D);
background(0);

textAlign(CENTER, CENTER);

fill(255, 0, 0);
textSize(48);
text("Season's Greetings!", width/2, height/3);

fill(0, 255, 0);
textSize(36);
text("OS: " + os, width/2, 2*height/3);

:)

1 Like