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

后端 未结 9 527
清歌不尽
清歌不尽 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 09:38

    If you want something that works well on windows there is a package called WinFoldersJava which wraps the native call to get the 'special' directories on Windows. We use it frequently and it works well.

    0 讨论(0)
  • 2020-11-22 09:39

    Alternative would be to use Apache CommonsIO FileUtils.getUserDirectory() instead of System.getProperty("user.home"). It will get you the same result and there is no chance to introduce a typo when specifying system property.

    There is a big chance you already have Apache CommonsIO library in your project. Don't introduce it if you plan to use it only for getting user home directory.

    0 讨论(0)
  • 2020-11-22 09:45

    Actually with Java 8 the right way is to use:

    System.getProperty("user.home");
    

    The bug JDK-6519127 has been fixed and the "Incompatibilities between JDK 8 and JDK 7" section of the release notes states:

    Area: Core Libs / java.lang

    Synopsis

    The steps used to determine the user's home directory on Windows have changed to follow the Microsoft recommended approach. This change might be observable on older editions of Windows or where registry settings or environment variables are set to other directories. Nature of Incompatibility

    behavioral RFE
    
    6519127
    

    Despite the question being old I leave this for future reference.

    0 讨论(0)
  • 2020-11-22 09:49
    System.getProperty("user.home");
    

    See the JavaDoc.

    0 讨论(0)
  • 2020-11-22 09:54

    The bug you reference (bug 4787391) has been fixed in Java 8. Even if you are using an older version of Java, the System.getProperty("user.home") approach is probably still the best. The user.home approach seems to work in a very large number of cases. A 100% bulletproof solution on Windows is hard, because Windows has a shifting concept of what the home directory means.

    If user.home isn't good enough for you I would suggest choosing a definition of home directory for windows and using it, getting the appropriate environment variable with System.getenv(String).

    0 讨论(0)
  • 2020-11-22 09:55

    I would use the algorithm detailed in the bug report using System.getenv(String), and fallback to using the user.dir property if none of the environment variables indicated a valid existing directory. This should work cross-platform.

    I think, under Windows, what you are really after is the user's notional "documents" directory.

    0 讨论(0)
提交回复
热议问题