为什么 "null" 在下面的代码中被视为字符串并连接到文件名?

Why is "null" treated as string here in the below code and is concatenated to the name of the file?

我有一个方法可以根据OS的类型检查操作系统类型和return合适的路径。此路径由接受此路径并将文件保存到 t 的另一种方法使用 帽子位置。现在,如果 OS 不是 Windows、Linux 或 Mac,则方法 returns null。问题是此 null 被视为字符串,并且 null 被添加到已保存文件的名称中,例如; nullFile.txt并保存到程序存放的位置。 我能做些什么来防止这种情况发生?

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;
}

你没有显示代码,但你可能正在做

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

在字符串连接中,null 值被转换为字符串 "null",因此您必须编写显式 null 检查代码。

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

至于 return 从 checkOS 中输入一个空字符串而不是 null 的选项,这是一种可能性,但在任何一种情况下, checkOS 的调用者都需要测试结果,因为我确定您想为这种情况做一些不同的事情。 null return 是最通用的选项。