-1

I have a method to check the operating system type and return a suitable path according to the type of OS. This path is used by another method which accepts this path and saves a file to t hat location. Now if the OS is not Windows, Linux or Mac then the method returns null. The problem is that this null is treated as a string and null gets added to the name of the saved file e.g; nullFile.txt and saves it in the location where the program is stored. What can I do to prevent this from happening?

public static String checkOS() {
    String store = "";
    String OS = System.getProperty("os.name").toLowerCase();
    if(OS.indexOf("win") >= 0){
        store = "C:/";
    } else if(OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ){
        store = "/home/";
    } else  if(OS.indexOf("mac") >= 0){
        store = "/home/";
    } else{
        return null;
    }
    return store;
}
bhatnaushad
  • 372
  • 1
  • 2
  • 16

1 Answers1

2

You don't show the code, but you're probably doing

String filename = checkOS() + "File.txt";

In String concatenation, null values are converted to the string "null", so you have to code an explicit null check.

String osName = checkOS();
String fileName;
if (osName == null)
    // do whatever you need to do
else
    filename = checkOS() + "File.txt";

As to the option of returning an empty string from checkOS instead of null, that is a possibility but in either case the caller of checkOS is going to need to test the result as I'm sure you want to do something different for that case. A null return is the most generic option.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • Good answer but why not just return a blank string in the checkos method and avoid all nulls? – SteelToe Mar 23 '18 at 05:15
  • That's another option, but either way the caller of `checkOS` will need to check the result because I doubt an empty string would be useful. You wouldn't want the output file to be named just `"File.txt"`. – Jim Garrison Mar 23 '18 at 05:20
  • Ah very true. I hear. – SteelToe Mar 23 '18 at 05:21
  • Yes right @JimGarrison . I want to prevent the file from saving in location other than that returned by checkOS() method. – bhatnaushad Mar 23 '18 at 05:23