1

Is there a way to get user's home directory from java code?

For example: my user's home directory absolute path is C:\Users\stanislav. If I type %HOMEPATH% in Windows file explorer it will open me my user's directory.

I want to get this directory as File from JAVA using this code:

final Path homePath = Path.of("%HOMEPATH%"); 
final File file = homePath.toFile();
file.exists() // returns false

But this path is not referred to any file or directory. Help please.

  • Try using System.getenv – cup Nov 24 '20 at 17:02
  • which one you prefer, `%HOMEPATH%` or users home directory? – eis Nov 24 '20 at 17:15
  • this question looks like duplicate of https://stackoverflow.com/questions/585534/what-is-the-best-way-to-find-the-users-home-directory-in-java, can you explain why it's not – eis Nov 24 '20 at 17:16

2 Answers2

2
String usersHomeDir = System.getProperty("user.home");
Thakur Amit
  • 357
  • 1
  • 4
  • 12
1

You can do

System.getProperty("user.home");

to get the home directory for the current user as a String. You can then pass the result to the File constructor to create a File object.

String home = System.getProperty("user.home");
System.out.println(home);  // prints the path to your home directory
File file = new File(home);
System.out.println(file.exists()); // prints true
hiroki
  • 21
  • 1
  • 6