What is the best way to find the users home directory in Java?

后端 未结 9 737
清歌不尽
清歌不尽 2020-11-22 09:12

The difficulty is that it should be cross platform. Windows 2000, XP, Vista, OSX, Linux, other unix variants. I am looking for a snippet of code that can accomplish this for

9条回答
  •  醉梦人生
    2020-11-22 10:01

    As I was searching for Scala version, all I could find was McDowell's JNA code above. I include my Scala port here, as there currently isn't anywhere more appropriate.

    import com.sun.jna.platform.win32._
    object jna {
        def getHome: java.io.File = {
            if (!com.sun.jna.Platform.isWindows()) {
                new java.io.File(System.getProperty("user.home"))
            }
            else {
                val pszPath: Array[Char] = new Array[Char](WinDef.MAX_PATH)
                new java.io.File(Shell32.INSTANCE.SHGetSpecialFolderPath(null, pszPath, ShlObj.CSIDL_MYDOCUMENTS, false) match {
                    case true => new String(pszPath.takeWhile(c => c != '\0'))
                    case _    => System.getProperty("user.home")
                })
            }
        }
    }
    

    As with the Java version, you will need to add Java Native Access, including both jar files, to your referenced libraries.

    It's nice to see that JNA now makes this much easier than when the original code was posted.

提交回复
热议问题